Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all 39796 articles
Browse latest View live

ADAFUN - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Alei Reyes
Tester-Pranjal Jain
Editorialist-Abhishek Pandey

DIFFICULTY:

Medium-Hard

PRE-REQUISITES:

Dp on Tries

PROBLEM:

Given a function $W$ and a set of non-negative integers $S_x$, you have to find the value $W$ takes if we remove $i'th$ element from the set. You need to do this for all $i=1$ to $N$. Please read rules to calculate $W$ from problem statement itself.

QUICK-EXPLANATION:

Key to AC- Realizing that we can build trie from Least Significant Bit (LSB) to Most Significant Bit (MSB). This allows us to see that at any time, the two leaves with deepest LCA (Least Common Ancestor) are the numbers to be removed from the set in this operation. Rest is application of dynamic programming on it.

The first thing to handle is finding which $2$ elements to remove from the set. Realize that, if we build trie from LSB to MSB, then automatically the leaf nodes with deepest LCA (LCA farthest from root) are the numbers to remove first. Hence, by doing a simple DFS on trie, we can find solution to the problem in a bottom-up manner.

Define a pair of two things $< W(u), R(u) >$. $W(u)$ represents the answer for $u$ and sub-tree for $u$, and $R(u)$ represent any of the remaining unpaired element. Say we need to calculate answer for parent of $u$, say $v$. We will this as follows-

$W(v)=W(u_1) \oplus W(u_2)$ where $u_1$ and $u_2$ are children of $v$. (If $v$ has only $1$ child, then take $W(u_2)=0$. If $v$ is a leaf, then $W(u_1)=0$ as well). Also, if both $u_1$ and $u_2$ both had an unpaired element, then we pair them both and additionally do $W(v)=W(v) \oplus [(R(u_1) \oplus R(u_2))-1]$.

$R(v)=$ Any unpaired element/leaf left in subtree. Note that, if $v$ is a leaf, then it is by default unpaired. Hence, if $v$ is a leaf, then $W(v)=0$ and $R(v)=val$ where $val$ is the value represented by the leaf.

Calculate $< W(u),R(u) >$ considering all elements in the trie.

Notice that when removing an element from the set, at most $\approx 60$ nodes will change their value. Values of rest of the tree will remain the same. Hence, we traverse back the required path to recalculate value if that particular element is absent, and get rest of the values by memoization

EXPLANATION:

Ouch, that was surely some "Quick" Explanation? :). If you're looking for a concise editorial, quick explanation has it all. In case one or more points are/were not clear, hop on to the appropriate section.

The quick explanation deals with all the important topics. We will elaborate the points on quick explanation, and proceed to conclude the editorial.

1. Handling the congruency thing.

At first sight, its not very trivial how we are supposed to get the two elements to pick from set.

Notice the effect of modulo $2^i$ operation. You will see that all bits after $i$ become $0$, and all bits from $[0,i)$ remain the same. An example to illustrate the point is in the tab below.

View Content

With this in mind, and lets see how to utilize this fact for our question. Usually, when we have to do such bit-wise operations, (eg- Find subarray with maximum XOR). The point is, that tries are something which we can think of when our problem involves a lot of bit manipulation (especially XOR).

Notice that, if we build the trie from LSB to MSB, we can solve this part efficiently. Think on what would a LCA of $2$ leaves mean in this regard. LCA of $2$ leaves will mean that, except for part from leaf to LCA, every other bit is same in both these numbers. Since we started from LSB to MSB, it will mean that every bit from LSB to the bit represented by LCA are same in those numbers. The farther this LCA from the root, the more bits in common we get.

Hence, the farthest leafs with farthest LCA from root will be removed first, and so on. Hence, this allows us to traverse the trie using DFS to calculate our dp values in a bottom up fashion.

2. How to use DFS with above observation to calculate Dps-

(Optional -If you are not sure on how bottom up DP is calculated, you can read the box below.)

View Content

One important thing to realize is that, we only care about which element to pair with whom, and not the order in which they are paired. In other words, say we know that $(a,b)$ are paired, then we dont care if we calculate $W(u) \setminus (a,b)$ first of $W(\{a,b\})$ first. $(\because A \oplus B \equiv B \oplus A)$.

To prove above, lets do a dry run. Say our current set to calculate $W$ of is $S_x= \{a,b,c,d,e\}$, and that we know that we have to pair $a$ with $b$ and $c$ with $d$. Hence, our $W$ is calculated as-

$W= W(a,b,c,d,e)= W(a,b) \oplus W(c,d,e) = (a \oplus b -1 \oplus [W(c,d) \oplus W(e)] = (a \oplus b -1) \oplus (c \oplus d -1) \oplus e$

If our pairing is correct, i.e. still pair elements as before, then we can as well remove pair $(c,d)$ first, as shown below-

$W= W(a,b,c,d,e)= W(c,d) \oplus W(a,b,e) = (c \oplus d -1) \oplus [W(a,b) \oplus W(e)] = (c \oplus d -1) \oplus (a \oplus b -1) \oplus e$

Hence, what we should realize is that, the condition of "has remainders congruent with highest power of $2$" is more to make us pair elements correctly, than to tell in which order we have to remove. You can find further discussion on it in next paragraph $-$ its not a very trivial observation to make, so take your time going through the proof and discussion.

For above point, lets take an example. Say, we are at node $u$, and there exists some leaves with deeper LCA, which are not in subtree of $u$ and are in, say, subtree of some other node $v$. Ask yourself, does calculating answer for subtree of $u$ first affect answer? Think a while. The answer will be in the box below.

View Content

The above two are important to realize the proof of correctness of DFS.

3. DP recurrences-

Notice that all the operations in calculation of $W$ (except the one where $W$ has two elements only) are $XORS$. As clear from above, we can compute answer for each sub-tree independently, as except the remaining unpaired leaves, all leaves in a subtree will be paired with each other. (When I say leaf, remember that leaves are storing the value of that element. So pair of leaves is another way of saying pairing of elements).

Realizing this, and it becomes easy to compute $W$. We first calculate $W$ for complete set. We will discuss removals soon. By expansion of $W$, and our subtree argument, lets reason out on the recurrence-

  • $W(v)=W(u_1) \oplus W(u_2)$ where $u_1$ and $u_2$ are children of $v$ - This part comes from the fact that, $W(u_1)$ and $W(u_2)$ are holding answers for elements/leaves which are paired in their subtree. The final answer, obviously depends on this. Also, we saw in expansion that final answer is XORSUM of different $W$ values, hence XOR of values of its subtree is done to find $W$. Obviously, if either or both of $u_1$ and $u_2$ do not exist, then their corresponding $W$ value is $0$.
  • If both $u_1$ and $u_2$ both had an unpaired element, then we pair them both and additionally do $W(v)=W(v) \oplus [(R(u_1) \oplus R(u_2))-1]$. - This part comes from the fact that, if a subtree has odd number of leaves, it means we will have one leaf left unpaired. Since we want to obey the condition of remainders being congruent to highest power of $2$, we wish to pair it as soon as possible with another unpaired leaf as we traverse the tree in a bottom-up fashion. Once we find another unpaired leaf to pair it with, we pair it and add the correspondign value to answer.
  • $R(v)=$ Any unpaired element/leaf left in subtree. Note that, if $v$ is a leaf, then it is by default unpaired. Hence, $R(u)$ just holds value of unpaired leaf/element and is easy to compute. If we have traversed the entire tree and still have an odd leaf (due to odd number of elements in the set), we use the definition of $W$ for a single element and XOR $W(R(u))$ with calculated answer.

Lets reason out on our base case for a leaf-

  • Leaf is a single element. Hence, no pairing is possible. $W(L)=0 \oplus 0=0$ as discussed in recurrence.
  • A single leaf is, by default, unpaired. Hence $R(L)=val$ where $val$ is value of element represented at leaf.

Now we will proceed to the last part of calculating the answer if an element from the set is removed. As a hint to people who want to try it themselves, its based on recalculating the value of $W$ by traversing the tree - using memoized values of $W$ for unchanged parts of tree, and hence calculating values for only leftover $log S_i \approx 60$ nodes of the tree.

An implementation of the function is to calculate recurrence is given below-

View Content

4. Dealing with removals.

One of the elegant ways of doing this, is calculate $W$ ignoring the leaf corresponding to element we have to remove. Most of the tree remains the same, only the $60$ nodes in trie corresponding to path to that leaf are to be handled.

Hence, what we do is, we start from root of the tree, and with initial value of answer as $0$. Now, we proceed with DFS as before. If the current node in DFS does not lie on path to removed leaf, we simply use back the memoized value. Else, if it lies on path to removed leaf, we recurse down the path to calculate answer with this leaf removed. This is equivalent to, returning a value of $< W(Leaf)=0,R(Leaf)=N/A>$ on reaching this leaf. Note that we are NOT traversing the entire trie again and again, we are just traversing the path to the removed leaf, and using the old memoized values we calculated earlier for parts where no change has occured.

A brief implementation of same can be found in tab below-

View Content

SOLUTION

Setter

View Content

Tester

View Content

$Time$ $Complexity=O(NLog S_i)$ where $S_i$ denotes the maximum value of an element in the set.
$Space$ $Complexity=O(N_logSi)$ where $S_i$ denotes the maximum value of an element in the set.

CHEF VIJJU'S CORNER :D

1. Setter's Notes-

View Content

2. Tester's Notes-

View Content

3. Related Problems-


ADASCOOL - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Alei Reyes
Tester-Pranjal Jain
Editorialist-Abhishek Pandey

DIFFICULTY:

Simple

PRE-REQUISITES:

Logic reasoning, Conditionals

PROBLEM:

You are given a $N*M$ matrix where every element can be swapped by its direct neighbour (up, down, left and right). Is it possible to swap them such that no element is at its original place?

QUICK-EXPLANATION:

Key to AC- Realize that answer is not possible only if $N$ and $M$ both are odd.

We can prove that, if at least one out of $N$ or $M$ is even, then an answer exists (Eg- say, if number of columns are even, then swap elements at column $1$ with those at column $2$, column $3$'s elements with column $4$'s etc.). However, if both $N$ and $M$ are odd, there will be at least $1$ student who cannot be fitted anywhere, making the answer as NO.

The implementation for iterating over all cells, checking the condition and updating answer is below-

View Content

EXPLANATION:

Since this is one of the simpler problems, the editorial will be written in a way as such, how you can think during contest to have solved this problem. We will start with analyzing trivial cases, and then expand them to complex ones , i.e., typical divide and conquer :) (Divide the problem into cases which are easy to conquer :p)

1. Trivial cases-

Lets forget that we have a matrix. Lets say that we only have $1$ row and $M$ columns. Lets analyze this scenario.

  • If $M$ is even, then we can swap students at column $1$ and $2$ with each other, elements at column $3$ and $4$ with each other and so on. Since $M$ is even, every student has been swapped.
  • If $M$ is odd, you will find that an answer cannot exist.

Lets analyze case of odd $M$ more deeply. Say, we take example of $M=3$. Say, the initial seating arrangement is like $1,2,3$. We need to make sure no element is at its place. But notice that $1$ and $3$ both have only $1$ option, i.e. $2$'s table. But only $1$ student per table is allowed, hence no answer.

Lets take another, $M=5$ now. We place $1$ at $2's$ place to get $.1...$ (supposing we are yet to seat rest of them). Now, if we seat $2$ at $1's$ place, we get a case similar to $M=3$ for $3,4,5$ and answer wont be possible. But, if we put $2$ at $3's$ position, it wont be possible to fill $1's$ place and hence $1$ student will still be left.

Nice!! We can extend this logic to claim that if there is only $1$ row, no answer exists for odd $M$. But, whats next?

2. Extending the Answer for $2-D$ Matrix-

Say now we have $N$ rows. Lets again make cases-

  • If $M$ is even, we can follow the pattern discussed earlier for every row and satisfy each row independently. Hence, answer exists.
  • If $M$ is odd - Can we claim that an answer wont exist? Or will we have to take $N$ in account??

Hmm, the $M$ being odd case is not so simple. Lets break it down further-

  • $N$ is even and $M$ is odd - Recall that we can swap $up$ and $down$ as well!! Hence, lets solve the problem independently for each column, by swapping students up and down. (An alternate way to look at it is, just rotate the matrix by 90 degrees such that rows become columns and vice versa. Now apply our previous procedure.)
  • If $N$ is odd and $M$ is odd - In our earlier analysis, when $N$ was $1$, the issues we faced were that, either the last element could not go anywhere, or the seat of first element was vacant. We can prove that the answer for such a case will not exist. The proof is below-

Lets use a chess board proof to prove above claim :)

Label any cell white. Its neighbors must be black. If $N$ and $M$ are both odd, then there are a total of odd number of cells, which means that number of white cells is NOT equal to number of white cells.

Ultimately, the operation asks us to place a white cell to its neighboring black one, and vice versa. But if number of white and black cells are not equal, we can see that there will always be $1$ student left out in every configuration. This completes the proof for non-existence of answer for odd $M$ and odd $N$.

SOLUTION

Setter

View Content

Tester

View Content

Editorialist

View Content

$Time$ $Complexity=O(1)$
$Space$ $Complexity=O(1)$

CHEF VIJJU'S CORNER :D

1. Prove that filling the matrix spirally wont work. (Hint: The last element becomes the middle element).

2. Prove or disprove that the analysis we did above is exhaustive. Did we leave out any possibility? Or did we cover them all due to the constraints of swapping only with neighbours?

3. If $N$ and $M$ are both $\leq 50$, is the value of $T\leq 5000$ reasonable? Can a smaller value suffice? Why/Why not?

4. Notice the spelling of School in Problem Code :D

5. Solve this alternate version of problem-

The problem is same, except that the rows are now, circularly arranged. Meaning, Row $1$ and Row $N$ are adjacent. Give a brief algorithm to solve the problem under this new constraint.

Hints-

View Content

6. Similar problems-

  • Trace - Based on analysis of 2-D matrices.

ADAMTR - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Alei Reyes
Tester-Pranjal Jain
Editorialist-Abhishek Pandey

DIFFICULTY:

Easy-Medium

PRE-REQUISITES:

2-Sat, DFS, Graph Coloring

PROBLEM:

Given $2$ matrices $A$ and $B$. In an operation, you can swap a row $i$ with column $i$. Tell if its possible to change matrix $A$ to matrix $B$.

QUICK-EXPLANATION:

Key to AC- See that swapping both row $i$ and row $j$ lead to same effect, i.e. element at $A_{i,j}$ remains at its position. Hence, we can make a logical expression, one for each row (whether to swap it or not) and solve it with $2-sat$.

OR

Key to AC- Identify it as a graph coloring problem with edges telling if nodes have to be of same color or not.

An element $A_{i,j}$ is swapped only if one of row $i$ OR row $j$. Swapping both of them leads $A_{i,j}$ to remain at its place. Hence, construct a graph with nodes from $1$ to $N$. Add an edge from every row $i$ to every other row $j$ with label telling if their color must be same (both swapped or both not swapped) or different (only one of them swapped). Now do $DFS$ on this graph to see if it can be colored under such constraints. Answer does not exist if coloring is impossible.

EXPLANATION:

We will be primarily discussing tester's graph coloring solution. Dont worry $2-SAT$ lovers, I am very sure that @alei will discuss his $2-Sat$ here(/* end of shameless advertisement of setter's blog*/).

We will first see that how the graph is formed, and then how to color it.

1. How to form the graph-

With regards to swapping row $i$ and row $j$, we have a total of $4$ choices -

  • Swap neither $i$ nor $j$ - No change to $A_{i,j}$ and $A_{j,i}$.
  • Swap row $j$ with column $j$ - $A_{i,j} \implies A_{j,i}$, i.e. both get swapped.
  • Swap row $i$ with column $i$ - $A_{i,j} \implies A_{j,i}$, i.e. both get swapped.
  • Swap BOTH row $i$ and $j$ - No change to $A_{i,j}$ and $A_{j,i}$.

Now, for every element of $A$ do the following-

  • If its not possible to make $A_{i,j}$ and $A_{j,i}$ same as corresponding elements in $B$ by given operations, print No
  • If $A_{i,j}==B_{i,j}$ and $A_{j,i}==B_{j,i}$, add an edge between Node $i$ and Node $j$ signifying that color of these $2$ nodes should be same.
  • If $A_{i,j} \neq B_{i,j}$ and $A_{j,i} \neq B_{j,i}$, we need exactly one swap. Add an edge from Node $i$ to Node $j$ signifying that these nodes must be of different color.

However, there is one case we failed to capture in above. If $A_{i,j}==A_{j,i}==B_{i,j}==B_{j,i}$ then this means we don't care if they are of same or different color. For such cases, we don't put any edge as edges are put to constraint the color of node. If there is no constraint, we do not add the edges.

A brief code to do this is below, in case you need help in implementation-

View Content

2. How to Color the Graph-

Its nothing but simple DFS for all the connected components in our graph (recall that we are not adding edges in some cases - the graph can be disconnected!!).

One of the ways to do it is, start DFS from any node of the connected component. Assign it some color, say $1$. If we travel an edge, flip color to $0$ OR keep it $1$ depending on what type of edge it is. If at any point of time, we arrive at an already colored node, and the color we need to assign to it is different from its current color, the answer would be $NO$.

An implementation of the DFS function is given below if anyone needs help-

View Content

SOLUTION

Setter - Using $2-SAT$

View Content

Tester - Using Graph Coloring.

View Content

$Time$ $Complexity=O(N^2)$
$Space$ $Complexity=O(N^2)$

CHEF VIJJU'S CORNER :D

1. Setter's Notes-

View Content

2. Tester's Notes-

View Content

3. You are given a general graph of $N$ nodes and $M$ edges. Can you give an algorithm to tell how many colors the graph needs to be colored - such that no $2$ adjacent nodes are of same color? What info do you need? (HINT: Degree of nodes...)

4. Given a tree of $N$ nodes, where $N \leq 10^{18}$, how many colors are needed for coloring it if adjacent nodes cannot have same color? How many colors does a $N*M$ bipartite graph needs? Can we draw some interesting observation from it?

Ans-

View Content

4. Related Problems-

ADAKNG - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Alei Reyes
Tester-Pranjal Jain
Editorialist-Abhishek Pandey

DIFFICULTY:

Cakewalk

PRE-REQUISITES:

Basic Looping, $2-D$ arrays, Conditionals, Greedy

PROBLEM:

A king is placed at cell $(r,c)$ $-$ $r$ being the row and $c$ being the column number. How many cells can it visit in at most $K$ moves?

QUICK-EXPLANATION:

Key to AC- Realize either of the $3$ things below-

  • Lets say we want to go at a cell at distance $(k_1,k_2)$. The optimal strategy is going diagonally until either $k_1$ or $k_2$ becomes $0$, and then moving horizontally or vertically (as we reached the same row/column now) until the cell is reached. Number of moves traversed are $max(k_1,k_2)$ .
  • This question is a standard BFS on matrix question.
  • The possible cells king can visit will form a square (or rectangle, depending on where he is placed). The area of this figure is the answer.

The quickest and most intuitive way to solve the problem is to realize that to go to a cell at distance of $(k_1,k_2)$ from our starting cell, we need $max(k_1,k_2)$ moves, for example, to visit cell $(X,Y)$ we get $k_1=|X-r|$ and $k_2=|Y-c|$. If the max of these if $\leq K$, we can visit this cell. Check this for every cell and print the answer.

EXPLANATION:

Most of the interesting stuff is there in quick explanation itself. We will simply expand some of the points, see the reasoning of why they occur and derive intuitions to solve such problems in the main explanation. However, the quick explanation section itself is self sufficient :).

1. A cell $(X,Y)$ can be visited if $max(|X-r|,|Y-c|) \leq K$

Lets say that the cell we're checking is $(X,Y)$. Let the distance of this cell from $(r,c)$ be defined as earlier, $(k_1,k_2)$. What happens when you move diagonally? You subtract $1$ from both $k_1$ and $k_2$. Had you moved horizontally, only one of them would have reduced, but because we moved diagonally, we came closer to the cell than we would have come by moving horizontally or vertically.

It is intuitive to see that, Greedy will hold. (Formally, it will hold true because there is no way we can come to a cell in lesser moves by visiting more cells). Hence, we move diagonally as long as we can. Without loss of generality, lets say $k_1 > k_2$. After moving diagonally for $k_2$ moves, the distance left to cover is now $(k_1-k_2,0)$.

Hence, total moves taken = $\underbrace{k_2}_ \text{Diagonally} + \underbrace{(k_1-k_2)} _ \text{Horizontally/Vertically}=k_1$ where $k_1$ was maximum of the two.

As an exercise - Repeat this proof taking $k_2$ as maximum and come to the same result.

2. Standard BFS on Matrix -

Who cares for observation when you can write a quick, bugless code for this algorithm within seconds? Well...technically you should care for observations because they make work quicker. :p

Anyways, theres nothing to tell here in this section, the exact standard algorithm is used. The reason I listed this out here is, because we all want some trivial problems on the algorithm after newly learning it. Mark this question as a good question for practice after learning this algorithm, even if it does seem like an overkill right now. The reason is, if you get a WA or RE in this question, then the fault will be in your BFS part - because thats the only part in this question. You'd hence save some time debugging while you discover an optimal way to implement the algo :)

3. Cells that king can visit will form a square/rectangle-

Setter's solution uses this

Say king is at middle of the chessboard. Refer to image below and observe the pattern-

alt text

  • $k=0-$ Only the cell he is lying on is visited.
  • $k=1-$ He can visit all cells immediately next to him. This is the yellow square in the picture Seems trivial till now?
  • $k=2-$ He can visit all cells on yellow square in $1$ move. We can see from picture that, he can visit all cells of orange square, from yellow square, in additional $1$ move. Hence, he can visit the cells in orange square in $2$ moves.

What about $k=3$? We can do a similar reasoning that, with $1$ more move we can visit all cells of green square from orange square.

From the picture, can we derive some formula for the length of this square? Yes!!

The king, in $k$ moves, can visit cells with column number from$[r-k,r+k]$ and row numbers between $[c-k,c+k]$. However, we also need to check that he does not fall off the board while doing so! (Eg- what if r=1 and k=5?). We see that, on adding the condition of not falling off the board, some rows/columns get removed from square and it becomes a rectangle.

Hence, our expression becomes-

$dx=min(c+k,8)-max(c-k,1)+1$ and $dy=dy=min(r+k,8)-max(r-k,1)+1$ where $dx$ and $dy$ are length of horizontal and vertical sides of rectangle. The $+1$ in the formula is to account for the row/column the king is standing it.

The area, i.e. $dx*dy$ is the answer.

SOLUTION

Setter - Used approach $3$.

View Content

Tester - Used approach $1$.

View Content

Editorialist - Used BFS

View Content

$Time$ $Complexity=O(1)$ for Setter $-O(N*N)$ for tester and editorialist where $N=$length of board
$Space$ $Complexity=O(1)$ for setter and tester $-O(N*N)$ for editorialist

CHEF VIJJU'S CORNER :D

1.Analyze how the question would be different if we replaced king with other chess pieces, say queen, rook, knight etc.
2.Give an algorithm to solve the modified version of the problem-

Instead of $8 \times 8$, the chessboard is of infinite size. You need to tell how many cells can be visited within $K$ moves $(1 \leq K \leq 10^9)$ if the piece we have is a-

  • King
  • Queen
  • Rook
  • Queen (If one of the dimension is finite)
  • Rook (If one of the dimension is finite)
  • Bishop (If one of the dimensions is finite)

Last three are difficult (in fact, you can find a question on the bishop case already). Just try to analyze for the king part and give your answer.

3.Related Problems-

ADAROKS - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Alei Reyes
Tester-Pranjal Jain
Editorialist-Abhishek Pandey

DIFFICULTY:

Medium-Hard

PRE-REQUISITES:

Bitmasking, Data Structures

PROBLEM:

Given a chessboard with kings placed on it, you need to find minimum number of rooks to place such that kings cannot reach each other. Rooks cannot be attacked by the kings for simplicity.

QUICK-EXPLANATION:

Key to AC- Realize that since $N*M \leq 1024$, at least one of the dimensions must be less than $32$. Now if we remove rows where kings are, and merge groups of empty rows into a single row, there can be at most $16$ rows where we can put rooks. Bitmasking + Clever Brute Force is the way to go.

Without loss of generality, assume $N \leq M$, otherwise we can simply transpose the matrix and obtain the same result. This caps $N$ to $N \leq 32$. Now, we need to see how many rows we can put rooks on. Out of these $32$ rows, remove rows where kings are placed as rook cannot be placed there without attacking the king. Once its done, see that you might get some consecutive rows which don't have king on them. Placing a rook on any of the row gives same effect, as long as we place it in the same column. Hence, merge them all into single row. We see that this limits maximum number of rows we can place rooks on to $N \leq 16$.

Try all possible subsets of rows on which we can place rooks. With rows decided, we now only need to see which columns we have to place rook. This problem can be shown equivalent to finding minimum number of lines to cut given set of intervals (where every interval must be cut by a line). The solution to this is, sort the intervals and greedily pick an interval to cut. All intervals intersecting with this interval are also cut by line and hence are removed. Repeat until no interval is left.

EXPLANATION:

The editorial will be modularized into parts. You can feel free to jump at and start from the part unclear to you, provided you are clear with the parts before it :)

1. How to arrive at $N \leq 16$ result-

First convince yourself that the board's area is $\leq 1024$. Now, this means, that at least one dimension must be $\leq \sqrt{1024}$, i.e. $\leq 32$. Without loss of generality, assume that $N \leq M$, as if thats not the case, we can rotate the matrix by $90^\circ$ and get same result.

Now, put kings alternatively on these $32$ rows. That is, keep one king at row $1$, next at row $3$...and so on. We see that we have exactly $16$ rows with kings, and $16$ free rows.

We are to see that we can, at no instance, have more than $16$ free rows. Now, addition of any more kings cannot increase number of free rows, as a rook cannot be placed in same row as of king. Also, if we remove any of the king, then the group of free rows will merge, again decreasing number of free rows. Also, we can see that the configuration we chose is a maximal one, no other configuration exists which has more free rows than this.

Hence, number of rows where rooks can be put (or free rows as I called earlier) are $\leq 16$

2. Getting bit-masking (without dp :p) into the picture-

The above observation of $N \leq16$ makes life veryy convenient. The reason being, now we have $2^16$ possible choices of keeping rooks on the rows. This is, $=65536$ combinations to try, at max. Hence, we can simply try all the combinations!

Once we are decided on which rows we have to put the rooks, I think you all can agree that the problem becomes somewhat simpler, and something which can be done with much less effort than what we imagined on reading the statement.

Next part deals with how to calculate the final answer. In case you wish to do an independent try without any more spoilers from editorial, this is your checkpoint :p

Calculating the final answer-

We store the column and row numbers of positions where kings are placed, so as to not to place rooks on them. Now, lets say we are placing rooks at row $i$ and row $j$, as per our current combination. Obviously, there should not be two kings on same column, else they can reach each other (recall that rooks are being placed ONLY at rows specified by our mask). Let me call the part of board bounded by row $i$ and row $j$ as $region$.

Now, you can model the problem as, "Given possible intervals of free columns, where we have to place rooks (recall we need to place rooks between $2$ kings in same region!), what are minimum number of rooks to place such that each interval has at least $1$ rook assigned to it."

The solution for this is to, sort all such intervals and greedily place rooks at larger interval, and eliminate intervals where rooks are already set.

"I cannot understand how to make these intervals."

In case those are your words, then read on :p

Now, for all columns from $[1,M]$, start from row $i+1$ and iterate up to row $j-1$. Make a vector $v$ to store column numbers of any kings up see. This ensures columns are put in sorted order in $v$.

Now, lets say we are looking at king present on index $idx$ on $v$. Our interval would be, all free columns after column of king at $v[idx-1]$ and all columns before those of king at $v[idx]$. A rough implementation is below-

View Content

SOLUTION

Setter

View Content

Tester

View Content

$Time$ $Complexity=O(2^{min(N,M)}*M*N)$
$Space$ $Complexity=O(N*M)$

CHEF VIJJU'S CORNER :D

1. Given $N*M$ dimensional chess board, how many knights can you put at it such that no knight attacks each other?Solution

2. Given a $N*N$ dimensional chess board, what if we ask to place bishops instead of knights in above problem. Can you draw a recurrence for it?Solution

3. Setter's Solution-

View Content

4. Tester's Solution-

View Content

5. Related Problems-

ADAPWNS - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Alei Reyes
Tester-Pranjal Jain
Editorialist-Abhishek Pandey

DIFFICULTY:

Easy- Medium

PRE-REQUISITES:

Observations, Game Theory, Grundy Numbers, Sprague Grundy Theorem

PROBLEM:

Treat the number of free moves for a pawn as pile of stones. The game hence reduces to, we can remove at most $2$ stones from $i'th$ pile and transfer it to $(i+1)'th$ pile. Stones moved from last pile are lost. We need to tell who wins given the starting configuration.

QUICK-EXPLANATION:

Key to AC- Correlation to Grundy numbers, applying Sprague Grundy theorem, and getting that only piles at even indices (starting from end) matter.

A number of observations are needed.

  • If we have a game where we can remove at most $K$ stones per turn, the grundy numbers for that pile repeat at $A_i\%(K+1)$
  • Grundy number of overall game is XOR of all piles, as per Sprague Grundy theorem.
  • Lets reverse the piles, so that its easier to denote and understanding. In this new pile, starting from first pile (the last pile in original configuration), only alternate piles matter. This is because, moving on moving stones from other piles, opponent can simply shift them to next pile by mirroring our move. As an example, say our piles were $(2,3,1)$. Reverse them. We get $(1,3,2)$. Any stone we move from the middle pile to last pile, is discarded by the opponent by mirroring our move on last pile.

With respect to above, the solution is simply XORSUM of grundy numbers all such alternate piles. The first player loses iff the XORSUM is $0$. An explicit formula can be seen as-

View Content

EXPLANATION:

The question was more on observation side. Hence, we will try to prove the observations in the main editorial. Calculation of answer from there, as shown in quick explanation, is trivial.

1. Reducing the problem into game of piles and stones.

This step is the basic foundation of our solution. Make sure to read it carefully.

Lets focus on $i'th$ pawn in initial configuration. Calculate how many moves it can move. We can treat this as number of stones on the $i'th$ pile.

More formally, in our reduction to game of piles and stones, we say that, $i'th$ pile has $K$ stones if the $i'th$ pawn can move $K$ steps in initial/given configuration.

As an example, for below configuration-

...P..P.P....

Our piles will be $(3,2,1)$ as first pawn can move $3$ steps before getting blocked, the second pawn can move only $2$ steps before being blocked by first pawn and so on.

Now, we need to define the operations.

A player can move a pawn at most $2$ steps. Say we are considering $i'th$ pawn. An operation on it will reduce number of steps this pawn can move by at most $2$, and increase number of steps $(i+1)'th$ pawn can move by same amount. This is, equivalent to moving at most $2$ stones from $i'th$ pile to $(i+1)'th$ pile.

Note that, if current pile is last pile, the stones are removed from the game (as there is no pawn after the last pawn to move on those free cells in original version).

2.If we have a game where we can remove at most $K$ stones per turn, the grundy numbers for that pile repeat at $A_i\%(K+1)$

Refer to example $2$ in the pre-requisite link of Grundy Numbers. Our proof is similar.

Say we have a pile of $N$ stones, and can remove exactly $1$ stone from it. Grundy number takes values from $0$ (if the first player immediately loses) else $mex(Position_i)$ where $Position_i$ is set of all possible game positions.

Lets analyze this for $N=1$ to $N=4$.

At $N=0$, first player loses. Grundy number is, hence, $0$. At $N=1$, he wins, hence the Grundy Number takes value of $1$. At $N=2$, the first player is bound to lose. This is same game position as have $0$ stones at start. Hence, Grundy is equal to $0$. For $N=3$, the first player wins by removing $1$ stone, as then player $2$ cannot win no matter what.

See the pattern. $GrundyNum=0,1,0,1,....$.

Lets take example where we can remove at most $2$ coins now. This is the situation in our current problem. Grundy numbers for a pile with $0$ coins is $0$, pile of $1$ coins is $1$. for a pile of $2$ coins, player $1$ wins by removing $2$ stones - this is a new gaming move/position, hence grundy number is $mex(0,1)=2$. At $N=3$, no matter what he does, the second player can win by removing $1$ or $2$ stones depending on what move player $1$ does. Hence, at $N=3$, player $1$ always loses, and its Grundy number is $3$ (position equivalent to pile with $0$ coins).

If we further work up examples for higher $N$, we see that $GrundyNum=0,1,2,0,1,2,0,1,2...$ which is basically $N\%3$

As an exercise, can you work on a formal, or at least intuitional proof for it? The answer is, as usual, in my Chef Vijju's Corner :D.

3. Starting from end, only alternate piles matter-

Lets say our piles are $(2,4,5,1,3)$. I claim that, piles at position $2$ and $4$, i.e. with stones $4$ and $1$, don't matter. Rest of the piles matter.

Let me denote the pile at $i'th$ position by $Pile_i$. Say I moved $2$ stones from $Pile_2$ to $Pile_3$, i.e. from Pile with $4$ stones to Pile with $5$ stones. The opponent can simple copy my move, and move those two stones from $Pile_3$ (one with $5$ stones initially) to $Pile_4$ (the one with $1$ stones initially).

More formally, if we move stones from non-significant piles, the opponent will simply put them back to a significant pile, which makes it equivalent to us putting stones from first significant pile to the next ourselves.

Also, another interesting question. What if we become stubborn, and keep removing stones only from non significant piles? (Hint: Think in terms of who gets to make the last move).

An alternative perspective is this-

Its a game of Nim in alternate piles, starting from last pile. In case a player moves on the insignificant piles, the winning player can simply copy his move and remove those stones from Nim piles by moving them to next insignificant pile, or eliminating them completely if current pile is last pile. This keeps configuration of Nim piles same, and hence losing player is still in losing position.

Let me summarize the various intuitions on why we are ignoring the insignificant piles -

  • If the losing player makes move on these piles, then winner can simply mirror it and move the piles to next insignificant pile, or even eliminate them if current pile was last pile.
  • If a player moves on these insignificant piles, then the other player gets to remove the stones, or move them to next insignificant pile. Hence, the other player is guaranteed another move.

4. Wrapping it up-

Once you see it in a perspective of a game of NIM in alternate piles, the problem becomes trivial. We simply start from end, and XOR the grundy numbers of every pile (which is $A_i \%3$) as in accordance to Sprague Grundy Theorem. If the final XORSUM is $0$, player $1$ loses, else he wins.

What is more difficult in the question is, getting the perspective. I will admit that once you get that its a game of NIM on alternate piles, its easy to prove things. But the real question is, how to get this observation in first place? For starters, I feel doing game theory questions based on Grundy numbers regularly is the way to go. This was just a game of nim on alternate piles, we never know what next twist is waiting for us there. :)

SOLUTION

Setter

View Content

Tester

View Content

$Time$ $Complexity=O(N)$
$Space$ $Complexity=O(N)$

CHEF VIJJU'S CORNER :D

1. Proof on Grundy Numbers-

View Content

2. Answer to the interesting observation in section 2.-

View Content

3. Derive Grundy numbers for a single pile, with stones from $N=1$ to $N=10$ if you are allowed to remove only $2$, $4$ or $5$ stones at once. Can we get a nice recurrence for it? Why/Why not?

4.Setter's Notes-

View Content

5. Tester's Explanation for Alternate Piles with an example-

View Content

6. An alternate intuition on insignificant piles-

View Content

7. Related Problems-

A doubt in approach of MAXEP problem ( Shared by IOI Gold Medalist ) - December long contest 2018

$
0
0

I wrote an editorial regarding how to solve the MAXEP problem asked in december long contest 2018.

A lot of users shared wonderful approaches to take on the problem (besides my way of solving it), but I was not able to understand the approach of @utaha.

So any-one who understands how @utaha solved that particular problem - Please help...!!!

Especially I would be glad if @utaha himself helps me...!!!

That approach was ( as @utaha mentioned in the editorial ) from an IOI gold medalist and sounded very simple, just the fact was that I was not able to understand why was it working...

Link to that editorial can be found HERE

I asked my doubts there in the comments section ( Just under where @utaha shared his approach), but I guess no one is looking at that editorial now... So I decided to ask it seperately here.

But if you get @utaha's approach, Please share it in that editorial itself. ( It will be good for me to have all material of one question under one link itself)

Thanks in Advance...!!!

TRICOIN - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Sunny Aggarwal
Tester:Sergey Kulik
Editorialist:Sunny Aggarwal

DIFFICULTY:

Cakewalk

PREREQUISITES:

Implementaion, Mathematics, Brute Force.

PROBLEM STATEMENT:

You are given a number $N$ that represents the number of coins you have and you have to print the maximum possible height $H$ of triangle which can be made from these coins in such a way that $i^{th}$ row of the triangle contains $i$ coins.

QUICK EXPLANATION:

Maximum possible height of the triangle is the maximum possible value of $H$ such that $\frac{H\times(H+1)}{2} \le N$.

EXPLANATION:

It should be noted that $i^{th}$ row of triangle contains $i$ coins. Therefore, a traingle with $H$ height will contain $1$ coin in $1^{st}$ row, 2 coins in $2^{nd}$ row, ... , $H$ coins in $H^{th}$ row and total number of coins required to build a triangle of height $H$ will be equal to

$$\sum_{\substack{1 \le i \le H}}{i} \quad = \quad \frac{H \times (H+1)}{2}$$

As we are asked to find the maximum possible height of the triangle, we have to find the maximum value of $H$ such that $\frac{H \times (H+1)}{2} \le N$. Note that the value of $N$ ~= $10^9$ in worst case and therefore the maximum possible value of $H$ will be order of $\sqrt{N}$.

We can use following simple procedure to solve this problem.

int sum(int h) {
    return (h * (h+1) / 2);
}

void solve() { int n; cin >> n; int h = 1; while(sum(h) <= n) { h ++; } cout << h - 1 << "\n"; }

TIME COMPLEXITY:

$O(\sqrt{N})$

BONUS:

Try solving same problem with $1 \le N \le 10^{15}$.

AUTHOR'S AND TESTER'S SOLUTION:

Author's solution can be found here.
Tester's solution can be found here.


NOSS - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:AmirReza PoorAkhavan
Tester:Danial Erfanian
Editorialist:Michael Nematollahi

PREREQUISITES:

DP, KNAPSACK

PROBLEM:

You are given a set of positive integers $a$. You are asked to replace any two of those numbers with any pair of positive integers so that the number of values you can obtain by adding up a subset of them (possibly empty) is maximized. You need to print this maximum number of values.

QUICK EXPLANATION:

The answer is "the maximum NOSS over all subsets of size $N-2$" $\times 4$.
Let's define $dp[i]$ as the number of subsets whose sum is equal to $i$. $dp$ can be calculated using the well-known knapsack problem.
Now, for each unique pair of numbers in the set, try removing them and calculating the NOSS of the rest of the numbers. It can be proven that the number of unique pairs of numbers in the set is of $O(S)$, where $S$ is the sum of all of the numbers in the set. You can remove the pair from the $dp$ array in $O(S)$ and then count how many of the slots in $dp$ are greater than $0$ modulo some big prime MOD (like $10^9 + 7$). The probability that those slots really contain $0$ and not just $0$ modulo MOD is very high. This way, we can calculate NOSS of the rest of the numbers.
This solution runs in $O(S^2)$.

EXPLANATION:

First of all, let's define $S$ as the sum of all the integers given in the input. The problem's description guarantees that $S \leq 10^4$.

Let's prove that there are at most $O(\sqrt{S})$ different numbers in $a$.
The proof is relatively simple. Let's assume that there are $K$ different numbers in $a$. Now, let's sort these $K$ numbers. The first one is at least $1$, the second one is at least $2$, the third one is at least $3$ and so on. This gives us $S \geq \frac{K \times (K+1)}{2}$. Hence, $K$ is of $O(\sqrt{S})$.

Since there are ${K+1}\choose{2}$ unique pairs of numbers to change, the abovementioned fact tells us there are at most $O(S)$ unique pairs of numbers to change.

The description of the problem tells us we can change two numbers to any natural number. Let's think of it as removing two numbers, making a new set out of the remaining $N-2$ numbers, and then adding two arbitrary numbers to that set. By adding a number to a set, its NOSS can get doubled at most; and we can achieve that increment by choosing a very large number to add. With the same reasoning, by adding two numbers we can increase the NOSS of the set $3$ times. Or in other words, we'd be multiplying the NOSS of the set of size $N-2$ by $4$. So all that's left is to calculate for each unique pair of integers from the set, what will the NOSS of the set be after removing them.

Let's define $dp[i]$ as the number of subsets of $a$ whose sum is equal to $i$. You can calculate this dp by inserting the numbers one by one, something like this:


for (int i = MAXN-1; i >= x; i--)
    dp[i] += dp[i-x];

Now let's iterate over all unique pairs of numbers from $a$ and try removing them from $dp$. The removal can be done like this:


for (int i = x; i < MAXN; i++)
    dp[i] -= dp[i-x];

After removing the pair, go through all the slots of $dp$ and count how many of them are greater than $0$. This gives us a solution of $O(S^2)$.

One problem remains though. The numbers in the $dp$ array can get arbitrarily large. To avoid overflow, we can do all of our calculations modulo some big prime called MOD. MOD can be $10^9 + 7$. The only problem with this approach is that if $dp[i] = 0$, we assume that $dp[i]$ really is equal to $0$ and not just equal to $0$ modulo MOD. But The probability of this assumption failing is low and thus this solution works.

Refer to the editorialist's solution to see the described solution.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here

Tester's solution can be found here

Editorialist's solution can be found here

Invitation to CodeCharades 2k19

$
0
0

Hola amigos..!
Tighten your seatbelts and be prepared with all your skillset ‘Coz it’s high time for a Code-storm where all the champions will thrive but only a few will survive. So here comes the very first edition of “CodeCharades”, an online competitive coding championship presented by Codechef Chapter: IIT Patna, in association with ANWESHA & CodeChef as coding partner..! And yes, the winners will be rewarded with amazing prizes worth ₹5k and 250 codechef laddoos(for top 3 partcipants).


Date and time: 21st Jan, 2019, 9PM-11PM.


The contest will be hosted on codechef.com .


P.S. We won't go easy on you!!!

Follow this link to register yourself for the contest... click here

!! FOR MORE INFORMATION !!
Follow this link for facebook page...
https://www.facebook.com/IITPCHEF

Follow this link for contest-
https://www.codechef.com/COCS2019

alt text

COOLING - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

EASY

EXPLANATION

The following greedy algorithm always finds the optimum answer:

  • Choose the lightest pie not yet on a rack

  • If none of the remaining racks can hold this pie, stop

  • Of all the racks that can hold this pie, place the pie on the rack with the smallest weight limit

  • If there are no more pies, stop. Otherwise, go back to step 1

TESTER'S SOLUTION

Can be found here.

CHEFCHR - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Shivam Rathore
Tester:Hanlin Ren
Editorialist:Hanlin Ren

DIFFICULTY:

CAKEWALK

PREREQUISITES:

None

PROBLEM:

Chef has a string consisting of only lowercase letters a-z. He wants to pick $4$ consecutive letters from the string such that the $4$ letters can be arranged into the word chef. Find the number of ways to do this.

EXPLANATION:

The solution is straightforward. Let the string be $s[0\dots(n-1)]$. Let's enumerate the start point of these letters, say $i$. Then $0\le i\le n-4$. The four letters are $s[i],s[i+1],s[i+2],s[i+3]$. To check if they can be arranged into chef, we can sort these letters and check if they form cefh in order. Let me explain in details.

Checking four letters

First, we need a subprocedure which given $4$ letters s1, s2, s3, s4, determine if they can be reordered into chef. Let's call it check(s1, s2, s3, s4). A method to do this is to sort the letters, and the result of sorting should be cefh. C++ code:

bool check(char s1, char s2, char s3, char s4) {
  char s[5] = {s1, s2, s3, s4, 0};
  sort(s, s + 4);
  return strcmp(s, "cefh") == 0;//strcmp returns 0 if two strings are equal
}

The 0 at the end of array s is necessary, since strcmp recognizes it as the end of string. Or, if you don't like strcmp, the last line can be written as

return s[0]=='c' && s[1]=='e' && s[2]=='f' && s[3]=='h';

The original problem

Given the subprocedure check, the rest is easy:

  • We enumerate the start $i$ of the four letters. Let $n$ be the length of string, we have $0\le i\le n-4$, and four letters are s[i], s[i+1], s[i+2], s[i+3];
  • If check(s[i],s[i+1],s[i+2],s[i+3]), the answer is increased by $1$;
  • At last, if answer is $0$, output normal; otherwise output lovely and the answer.

Code:

n = strlen(s); //s[0..n-1]
answer = 0;
//check all possible i's
for (i = 0; i <= n - 4; i++)
  if (check(s[i], s[i + 1], s[i + 2], s[i + 3]))
    answer += 1;
//output answer
if (answer == 0) printf("normal\n");
else printf("lovely %d\n", answer);

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.
Tester's solution can be found here.

Why have I not received laddus?

$
0
0

I participated in Plinth-Enigma'19 LNMIIT Techfest and ranked 6th. According to the rule, I should have been awarded 300 laddus. Can anyone please explain?

MGAME - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Smit mandavia
Tester:Xiuhan Wang
Editorialist:Taranpreet Singh

DIFFICULTY:

Easy

PREREQUISITES:

Modulo operator and Basic Combinatorics.

PROBLEM:

Given two integers $N$ and $P$, suppose the maximum value of $(((N \bmod i) \bmod j) \bmod k ) \bmod N$ be $M$ where $i, j, k \in [1, P]$, Find the number of ways to select $i, j, k \in [1, P]$ such that $(((N \bmod i) \bmod j) \bmod k ) \bmod N$ equals $M$.

SUPER QUICK EXPLANATION

  • The maximum value of $N \bmod x$ where $x \in [1,N]$, if $N$ is odd, is $(N-1)/2$ when $x = (N+1)/2$, and if $N$ is even, is $N/2-1$ when $x = N/2+1$.
  • We can achieve $(((N \bmod i) \bmod j) \bmod k ) \bmod N = M$ in three ways. Let $x = \lceil (N+1)/2 \rceil$
  • $i = x$ and $j,k > M$.
  • $i > N$, $j = x$ and $k > M$.
  • $i, j > N$ and $k = x$. Each of this case can be easily computed.

EXPLANATION

First of all, Let is find this value $M$. It has to be less than $min(i,j,k,N)$ which implies, $M < N$. Hence, if we want $M > 0$, we need $(((N \bmod i) \bmod j) \bmod k) < N$. So, We know for sure, that to maximize $M$, $min(i, j, k) \leq N$. Hence, we need maximum $(((N \bmod i) \bmod j) \bmod k) < N $ and now we can ignore the last $\bmod N$.

So, The maximum $N \bmod x$ can attain is $\lfloor (N-1)/2 \rfloor$. This happens when $x = \lceil (N+1)/2 \rceil$. It can be easily verified either by checking by hand, or writing a simple program ;)

Now, try finding out number of ways $(((N \bmod i) \bmod j) \bmod k)$ equals $M$. It can be approached in Simple case base analysis.

We can try all possible triplets of $(i,j,k)$ and generalize them into three cases.

  • When $i = \lceil (N+1)/2 \rceil$ and $j,k > M$
  • When $i > N$, $j = \lceil (N+1)/2 \rceil$ and $k > M$
  • When $i,j > N$ and $k = \lceil (N+1)/2 \rceil$

In all three cases, we can simply count the number of triplets $(i, j, k)$ satisfying any condition and print the answer.

Corner Case

When $N \leq 2$, $M = \lfloor (N-1)/2 \rfloor = 0$. This is because we cannot achieve $(((N \bmod i) \bmod j) \bmod k ) \bmod N > 0$. So, all triplets $(i, j, k)$ are valid.

Alternate solution - read at your own risk, you have been warned :D

For those curious enough not to be satisfied with such solutions, there also exists a pattern based solution too, using basic math. Just use brute solution to find the first terms of series and solve using the pattern formed. Number 6 is important. Enjoy :D

Time Complexity

Time complexity is $O(1)$ per test case.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution
Tester's solution
Editorialist's solution

Feel free to Share your approach, If it differs. Suggestions are always welcomed. :)

A good start to competitive programming for a newbie?

$
0
0

I am new to codechef. BUt I am not able to understand how to solve questions on codechef. All the question that I see look difficult to me. I am completely noob to competitive programming. Any advice, that will help to to get a better start is more than just welcome here.

PS Sorry for my english. :(


Java(hotspot) 8u112

$
0
0

i am not able to code with this platform EX : Integer.parseInt(sc.nextLine()); is not supporting in this, can you please help me

PRPALIN - Editorial

$
0
0

PROBLEM LINK:

Practice

Author:ADMIN

Editorialist:SUSHANT AGARWAL

DIFFICULTY:

SIMPLE

PREREQUISITES:

Basic looping,Conditional statements

PROBLEM:

You will be given an integer N, 1 ≤ N ≤ 1000000. You must find the smallest integer M ≥ N such that M is a prime number and M is a palindrome.

EXPLANATION:

Check every odd number after N (using a loop) for 2 properties

1)It should be prime 2) The number should be equal to its reverse.

Print the first number that satisfies these 2 properties and then break out of the loop when this number is encountered.

EDITORIALIST'S SOLUTION:

Editorialist's solution can be found here.

ANUGCD - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Anudeep Nekkanti
Tester:Mahbubul Hasan
Editorialist:Jingbo Shang

DIFFICULTY:

Medium

PREREQUISITES:

Segment Tree, Factorize

PROBLEM:

Given N numbers in a sequence, answer M queries about what is the maximum number between L and R and the greatest common divisor between it and G is greater than 1.

EXPLANATION:

Every number X can be written in the factorized form: X = p1^k1 * p2^k2 * ... * pi^ki * ... * pn^kn. We can call all pi as X's factors (of course, pis are all different primes). For example, 18 = 2 * 3^2. So we can say that 18, has factors 2 and 3. Because pi>= 2, the number of factors, i.e. n, is in O(logX). Therefore, the total number of factors of the given N numbers are O(NlogN) (the range of N and numbers are same).

The greatest common divisor of two numbers is greater than 1, means that they have at least one common factor. If we enumerate the common factor C they have, the satisfied numbers are determined -- all numbers have factor C. After that, the only thing we need is to find the maximum in the query interval [L, R]. For this type of queries, an ordinary solution is to use Segment Tree.

With these two ideas in mind, let's start to assemble the whole algorithm, now.

  1. Factorize N numbers, and restore some vectors of position[pi], which records the positions of the numbers who has the factor pi. From the analysis above, we know that the sum of position[pi].size() is O(NlogN)
  2. Build several segment trees, the i-th one corresponds to the position[pi], maintaining the interval maximum in the tree node. Of course, you can also concate all position and make a whole segment tree.
  3. For a query number X and the interval [L,R], first factorize X. And for each factor, look up in the corresponding segment tree (or corresponding intervals, if you choose to build a whole segment tree) to get the maximum. Finally, take the maximum of the query results among different factors.

As analyzed before ,X has at most O(logX) factors. And each interval-maximum query takes only O(logN) time. Therefore, to answer a query, our algorithm only needs O(log^2 N) time.

In summary, the time complexity is O(NlogN + Qlog^2N), while O(NlogN) space needed.

As requested by many users here are solutions without segment trees.
Sqrt-Decomposition.
Binary Indexed Tree.
STL-MAP

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.
Tester's solution can be found here.

Hints/Editorials - INOIPRAC problems

$
0
0

TSECJC02 - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:tseccodecell

DIFFICULTY:

Easy

PREREQUISITES:

Primality test

PROBLEM:

Given the first two numbers of a sequence $F1$ and $F2$, you have to generate a sequence such that $F_{i+2}=F_{i+1}+F_i$. You have to find the number of prime numbers from $F1$ to $F20$.

QUICK EXPLANATION:

Generate the 20 numbers. Count the number of prime numbers among these using a primality test.

EXPLANATION:

Generate the sequence using a simple loop. Only the last two values in the sequence need to be stored. As the numbers are being generated, check for primality and adjust the counter. Note: Also check the first two numbers which are given as input.

For checking whether a number is prime or not, a simple loop which tests whether a number $n$ is divisible with any number till $\sqrt{n}$ should suffice.

A faster solution is to use Sieve of Eratosthenes. First, make a boolean array of size $N$, initialising all the values as false. $N$ is the value till which we want to check for primes ($10^6$ should suffice). Starting from 2, check every multiple of 2 and mark it as true. After that, consider the next value of 2 which is still marked as false, 3. Mark all multiples of 3 as true. Since 4 is marked true, we skip it and move on to 5. We mark all multiples of 5 as true. We continue doing this till $\sqrt{N}$ ($10^3$ if $N=10^6$).

Other efficient primality tests can also be used to solve the problem.

SOLUTION:

Author's

Tester's

Viewing all 39796 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>