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

FREPPN - App (Review Requested)

$
0
0

Hello guys,

I was requested by @Codeiatio to write an app review on discuss for their app Freppen (@freppn) (link- https://play.google.com/store/apps/details?id=com.freppn.codeiatio.freppn ) for they feel their app has some potential to offer for you guys. Their idea is to connect people with everything in one place. They offer account linkings with sites like codeforces, github, linkedin and even some miscellaneous ones like Facebook, Twitter etc. They plan to combine social media with other mundane aspects like competitive coding, hobbies etc. One of their main features in this regard is making plans, for peer online competitive coding to sending each other memes (lol). Again, their idea is more on connecting people together which they offer via giving a vast amount of activity choices and ease of use. You will need to verify your account though, fake accounts are not allowed.


GCDMOD - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Bhuvnesh Jain

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

EASY-MEDIUM

Prerequisites

GCD, Modular Exponentiation, Overflow-handling

Problem

Find the GCD of $A^N + B^N$ and $(A - B)$ modulo $1000000007$.

Explanation

The only property required to solve the complete problem is $GCD(U, V) = GCD(U % V, V)$. If you are unfamiliar with this, you can see the proof here.

Now the problem remains finding the value of $(A^N + B^N) % (A - B)$. This is can be easily done using modular exponentiation in $O(\log{N})$ complexity. You can read about on wikipedia and implementation at Geeks for Geeks.

With the above 2 things, you are almost close to the full solution. The only thing left now is to handle overflows in languages like C++ and Java. First, understand why we might get overflow and then how we handle it.

Note that we are computing $A^N % (A - B)$. Since, $(A - B)$ can be of the order ${10}^{12}$, the intermediate multiplications during exponentiation can be of the order of ${10}^{12} * {10}^{12} = {10}^{24}$ which is too large to fit in long long data type. Due, to overflows, you will get the wrong answer. To deal with overflows, below are 3 different methods:

  • Using "int_128" inbuilt datatype in C++. For details, you can refer to [mgch solution].

This approach has a complexity of $O(1)$.

  • Using an idea similar to modular exponentiation. Instead of carrying out multiplication operations, we use addition operations. Below is a pseudo-code for it:

    # Returns (a * b) % m
    def mul_mod(a, b, m):
        x = 0, y = a
        while b > 0:
            if b & 1:
                # No overflows in additons.
                x = (x + y) % m
            y = (y + y) % m
            b >>= 1
        return x

This approach has a complexity of $O(\log{B})$.

  • Using idea similar to karatsuba trick. This is specific only to this question as constraints are upto ${10}^{12}$ and not ${10}^{18}$. We can split $a$ as $a_1 * {10}^{6} + a_2$ and $b$ as $b_1 * {10}^{6} + b_2$. Note that all $a_1, b_1, a_2, b_2$ are now less than or equal to ${10}^{6}$. Now we multiply both of them and there will be no overflow now in intermediate multiplications as the maxmium value can be ${10}^{12} * max(a_1, b_1) = {10}^{18}$. The setter code using this approach.

The time complexity of this approach is $O(1)$.

The final corner case to solve the problem is the case when $A = B$. This is because calculating $A^N + B^N % (A - B)$, would lead to runtime error while calculating modulo $0$. For this case, we use the fact that $GCD(U, 0) = U$. Thus the answer is simply $A^N + B^N$.

The last part is just printing the answer modulo $1000000007$.

The overall time complexity is $O(\log{N} + \log{max(A, B)})$. The first is for calculating the modular exponentiation and the second part is for calculating GCD. The space complexity is $O(1)$.

Once, you are clear with the above idea, you can see the author implementation below for help.

Note that since the number of test cases was small, another approach which iterates over divisors of $(A - B)$ to find the answer will also pass within the time limit if proper care is taken of overflows and the case $A = B$.

Feel free to share your approach as well, if it was somewhat different.

Time Complexity

$O(\log{N} + \log{max(A, B)})$

Space Complexity

$O(1)$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

mgch's solution can be found here.

GCDMOD - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Bhuvnesh Jain

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

EASY-MEDIUM

Prerequisites

GCD, Modular Exponentiation, Overflow-handling

Problem

Find the GCD of $A^N + B^N$ and $(A - B)$ modulo $1000000007$.

Explanation

The only property required to solve the complete problem is $GCD(U, V) = GCD(U % V, V)$. If you are unfamiliar with this, you can see the proof here.

Now the problem remains finding the value of $(A^N + B^N) % (A - B)$. This is can be easily done using modular exponentiation in $O(\log{N})$ complexity. You can read about on wikipedia and implementation at Geeks for Geeks.

With the above 2 things, you are almost close to the full solution. The only thing left now is to handle overflows in languages like C++ and Java. First, understand why we might get overflow and then how we handle it.

Note that we are computing $A^N % (A - B)$. Since, $(A - B)$ can be of the order ${10}^{12}$, the intermediate multiplications during exponentiation can be of the order of ${10}^{12} * {10}^{12} = {10}^{24}$ which is too large to fit in long long data type. Due, to overflows, you will get the wrong answer. To deal with overflows, below are 3 different methods:

  • Using "int_128" inbuilt datatype in C++. For details, you can refer to [mgch solution].

This approach has a complexity of $O(1)$.

  • Using an idea similar to modular exponentiation. Instead of carrying out multiplication operations, we use addition operations. Below is a pseudo-code for it:

    # Returns (a * b) % m
    def mul_mod(a, b, m):
        x = 0, y = a
        while b > 0:
            if b & 1:
                # No overflows in additons.
                x = (x + y) % m
            y = (y + y) % m
            b >>= 1
        return x

This approach has a complexity of $O(\log{B})$.

  • Using idea similar to karatsuba trick. This is specific only to this question as constraints are upto ${10}^{12}$ and not ${10}^{18}$. We can split $a$ as $a_1 * {10}^{6} + a_2$ and $b$ as $b_1 * {10}^{6} + b_2$. Note that all $a_1, b_1, a_2, b_2$ are now less than or equal to ${10}^{6}$. Now we multiply both of them and there will be no overflow now in intermediate multiplications as the maxmium value can be ${10}^{12} * max(a_1, b_1) = {10}^{18}$. The setter code using this approach.

The time complexity of this approach is $O(1)$.

The final corner case to solve the problem is the case when $A = B$. This is because calculating $A^N + B^N % (A - B)$, would lead to runtime error while calculating modulo $0$. For this case, we use the fact that $GCD(U, 0) = U$. Thus the answer is simply $A^N + B^N$.

The last part is just printing the answer modulo $1000000007$.

The overall time complexity is $O(\log{N} + \log{max(A, B)})$. The first is for calculating the modular exponentiation and the second part is for calculating GCD. The space complexity is $O(1)$.

Once, you are clear with the above idea, you can see the author implementation below for help.

Note that since the number of test cases was small, another approach which iterates over divisors of $(A - B)$ to find the answer will also pass within the time limit if proper care is taken of overflows and the case $A = B$.

Feel free to share your approach as well, if it was somewhat different.

Time Complexity

$O(\log{N} + \log{max(A, B)})$

Space Complexity

$O(1)$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

mgch's solution can be found here.

PROBLEMS - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Ashesh Vidyut

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

EASY

Prerequisites

Sorting

Problem

Given $P$ problems, each having $S$ subtasks. Each subtask has a score and the number of users successfully solving it. First, sort the subtasks for each problem in increasing order of subtask score. Now, calculate the number of valid indices such that the number of users solving that subtask is greater than the next higher subtask. This number, $n$ is the difficulty of the task.

Sort, the task in increasing order of difficulty.

Explanation

You are required to do whatever is just stated in the problem statement. In most languages, there is a support for "pairs" which is sorted internally in exactly the manner stated in the problem. Pair $(x, y)$ is smaller than $(u, v)$ is $x < u$ or ($(x == u)$ and $y < v$).

Further reading material for custom pair sorting comparators in C++ can be found here. For Java, you can read it here. In Python, pairs are represented as tuples. You can read more about it here.

The time complexity of the above approach will be $O(P * S * \log{S} + P * \log{P})$. The first term is for sorting the subtask list of each of the $P$ problem. The second term is for the sorting the final list of problems based on difficulty.

The space complexity will be $O(P + S)$. Note that it is not important to store all the subtasks for every problem which would lead to memory usage of $O(P * S)$.

Once, you are clear with the above idea, you can see the tester implementation below for help.

Feel free to share your approach, if it was somewhat different.

Time Complexity

$O(P * S * \log{S} + P * \log{P})$

Space Complexity

$O(P + S)$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

SHKNUM - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Jitender Sheora

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

SIMPLE

Prerequisites

Pre-computation, Binary-search

Problem

You are given a number $N$ and you can apply 2 type of operations:

  1. Add 1 to the number.
  2. Subtract 1 from the number.

Find the minimum number of operations to be carried such that the resulting number can be represented as $2^x + 2^y$, where $x$ and $y$ are non-negative and $x != y$.

Explanation

The first thing to note is the optimal answer requires us to apply the only operation of either type. Since the operations negate the effect of each other, we should either only add or subtract from our initial number $N$.

Suppose, if we have a sorted list of all possible final numbers which can be represented in the form, $2^x + 2^y$, then we can simply find the number nearest to $N$. For the smaller number, we can simply apply subtraction operation and for the greater number, we can simply apply the addition operation.

For finding the nearest number greater than or smaller than a given number, we can simply binary search. If you are not familiar with this, you can read topcoder tutorial. There are also inbuilt-functions like "lower_bound" and "upper_bound" in C++ which do your job. (But remember your list should be sorted.)

We can now pre-computate all possible numbers which can be represented in the form $2^x + 2^y$. Below is a pseudo-code for it:


    vals = []
    for i in [0, 30]:
        for j in [i+1, 30]:
            x = (1 << i) + (1 << j)
            vals.append(x)

Note that the maximum possible exponent of $2$ in answer can be $ceil(\log{{10}^9}) = 30$. This is because, for the minimum operation, we need to find the nearest possible number closest to $N$.

The size of $vals$ will be $(31 * 30) / 2) = 465$. Since the size is not large, even iterating through all numbers, instead of applying binary search will pass for the full solution.

Once, you are clear with the above idea, you can see the author or editorialist implementation below for help.

Feel free to share your approach, if it was somewhat different.

Time Complexity

$O({\log}^2{N})$ for pre-computation.

$O({\log{|vals|}})$ per test case.

Space Complexity

$O({\log}^2{N})$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

KCOMPRES - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Bhuvnesh Jain

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

MEDIUM

Prerequisites

Binary Search, Greedy, Segment trees.

Problem

You are given a sequence of integers $A_1, A_2, \dots, A_N$. For an integer $K$, let's define a $K$-compressed sequence $B_1, B_2, \dots, B_N$ as follows:

  • for each valid $i$, $B_i$ is a positive integer.
  • for each valid $i$, if there are exactly $X$ numbers smaller than or equal to $A_i$ in the subsequence $A_{\mathop{max}(1, i-K)}, \dots, A_{\mathop{min}(N, i+K)}$, then there must be exactly $X$ numbers smaller than or equal to $B_i$ in the subsequence $B_{\mathop{max}(1, i-K)}, \dots, B_{\mathop{min}(N, i+K)}$.
  • $B_1 + B_2 + \dots + B_N$ is minimum possible.

For a given integer $S$, find the number of values of $K$ ($0 \le K \le N$) such that the sum of elements of the $K$-compressed sequence does not exceed $S$.

Explanation

Let us first understand how to construct a $K-compressed$ array $B$ for given array $A$ and value $K$. For this, we will iterate over the numbers in increasing order and try to assign the smallest number not yet assigned to any number smaller than it until now. This will be optimal as we try to assign the smallest possible number to each number and iterating in increasing order ensures that if the number assigned to a given number can't be decreased further, the sum can't be minimised further. This proves our greedy strategy. Let me explain it through an example, where $A = [4 2 8 1 4 3 8 1]$ and $K = 3$.

Let the current array $B$ be $[-, -, -, -, -, -, -, -]$. We now group the numbers having the same value and iterate in increasing order. The following are the values of the array $B$ after each step:

  1. $[-, -, -, 1, -, -, -, 1]$. Since both $1$ are the first number to be considered, we assign them the smallest possible number in $B$, i.e. $1$.

  2. $[-, 2, -, 1, -, -, -, 1]$. Since, index $2$ has number $1$ less than it in range $[max(1, 2-3), min(8, 2+3)] = min[1, 5]$. We assign it the next biggest number.

  3. $[-, 2, -, 1, -, 2, -, 1]$. Since, index $6$ has number $1$ less than it in range $[3, 8]$, we assign it next highest number not present in this range i.e. $2$. Note that though $A[2] < A[6]$, we can still have $B[2] = B[6]$ as there ranges do not coincide to give a conflict.

  4. $[3, 2, -, 1, 3, 2, -, 1]$. For both index $1$ and $5$, we have it as the third largest number in their respective range. So, we assign them the next biggest number which was not used.

  5. $[3, 2, 4, 1, 3, 2, 4, 1]$. This is similar to the above process.

Thus, the minimum possible sum is $(3+2+4+1+3+2+4+1) = 20$. Make sure you are clear with the idea before you proceed further.

Now there are some issues which might occur while implementing the above approach. The first thing is that we should deal with all the numbers having the same value together should be dealt together instead of simply iterating in increasing order. One simple counterexample for this is the array $A = [10, 30, 30, 20, 10]$ and $K = 1$. The compressed array should be $B = [1, 3, 3, 2, 1]$ itself but if we simply iterate over numbers in increasing order, we might end up getting array $B$ as $[1, 2, 3, 2, 1]$ or $[1, 2, 2, 2, 1]$ which is again highly dependent on your implementation.

The correct logic is to first group the numbers by their values. Find what value you might end up giving them based on their ranges. Then, we need to be sure that the value we might give is correct or now. For this, we again iterate over the numbers and group them if their ranges coincide with each other. We assign it the all the numbers in the group the largest number we thought of assigning to any number in the range. For the example $A = [10, 30, 30, 20, 10]$ and $K = 1$, the process is as follows:

  1. The initial array is $[-, -, -, -, -]$.

  2. $[1, -, -, -, 1]$. We group $10$ first. The ranges for them are $[1, 2]$ and $[4, 5]$. Since they do not conflict, we assign them separately the minimum number to them. Both of them end up getting $1$.

  3. $[1, -, -, 2, 1]$. Since there is only one $20$, we simply assign it the smallest number in the range $[3, 5]$ which is not assigned yet, i.e. $2$.

  4. $[1, 3, 3, 2, 1]$. The ranges for $30$ are $[1, 3]$ and $[2, 4]$. Since they both coincide, we will assign them value together. The value we might end up giving $A[2]$ is $2$ since it is the smallest which is not used till now in the range $[1, 3]$ in $B$. The value we might end up giving $A[3]$ is $3$, which is the smallest not used till now in the range $[2, 4]$ for $B$. Since the ranges coincide, we should give each of them $3$, the maximum of the number we might think of assigning them.

Thus, we can easily build the $K-compressed$ algorithm using the above ideas. But how fast can we do it?

Doing it naively will take $O(N^2)$ as it will require you to find the smallest number not assigned yet in a range, taking $O(N)$ for this step alone. But if you restate this problem, it is similar to the following $2$ operations:

  • Update the number at given index.
  • Find the largest number in a range.

This is a very familiar problem which can be solved using segment trees in $O(\log{N})$ for each operation. You can read about it here.

Thus, we can built a $K-compressed$ array for given array $A$ and $K$ in $O(N * \log{N})$ complexity.

To find what possible values of $K$ will lead to compressed array having sum less than $S$, we can simply iterate over all possible values of $K$ and update the answer. This approach has a complexity of $O(N * N * \log{N})$ which is enough to pass the first $2$ subtasks.

The next thing to note that we can binary search on the answer. To prove this, we need to prove that the minimum sum for $K-compressed$ array does not decrease with increasing $K$. This again relies on the way we build our $K-compressed$ array using a greeedy algorithm. Since we make sure that each number is compressed to the smallest possible value and the sum can't decrease with increasing $K$ as the smallest number which might get assigned to a number can only increase if it's range (or window) increases.

Thus, the overall complexity of the approach reduces to $O(N * {\log}^2{N})$. This is enough to pass all the subtasks as well.

Once, you are clear with the above idea, you can see the author implementation below for help.

Feel free to share your approach as well, if it was somewhat different.

Note from Author:

The test case data was bit weak for the small subtasks where some wrong greedy approaches passed as well. Though the large test case ensured, wrong solutions could not pass for the full solution, but still, I failed in generating stronger test data for smaller ones. This is not completely our fault as there are many ways the greedy solution for this compression could be written where even index errors could happen which implementing. I would like to thank all the people who testing their solutions as well and helped me strengthen the test as well (Special thanks to Stepan). But still, we alone cannot come up with all possible greedy solution which one might write, so stronger test could not be prepared by me. By the time, I came to know about this it was already to late for a rejudge, but I will take care of it in the future problem.

Also, the problem statement seemed quite tough to comprehend for most of the contestants as well. User acmonster even pointed out a flaw in the English statement as well. Below were his comments:

"I guess that the problem (and test data) actually requires that sequence B should preserve all the relative sizes for each index pair (i, j) such that |i - j| <= K. In other words, if A[i] < A[j], we should have B[i] < B[j]; if A[i] = A[j], we should have B[i] = B[j], etc. If this is correct, the fix does not seem to be sufficient. Consider A = (1, 1, 1, 2, 3), B = (2, 1, 1, 1, 2), and K = 2: both sequences has a "signature" of (2, 2, 2, 2, 2), but, again, the optimal sequence B does not preserve A[1] = A[2] = A[3] < A[4] < A[5]."

Though most of the contestants got what the problem statement meant, I will make sure to make better statements in future as well.

Time Complexity

$O(N * {\log}^2{N})$

Space Complexity

$O(N)$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

SPELLBOB - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Praveen Dhinwa

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

CAKEWALK

Prerequisites

Looping Techniques

Problem

You are given 3 cards with letters written on both sides. You can permutate the cards or flip them. After you do all operations, the cards should spell "Bob" on the top face.

Explanation

First, fix the letter $o$ for the middle card. Now, try the remaining cards and check if both of them contain a "b" on either side of them. A pseudo-code for the above approach is:


    s = input()
    t = input()
    for i in [0, 2]:
        if s[i] == 'o' or t[i] == 'o':
            cnt = 0
            for j in [0, 2]:
                if j != i:
                    if s[j] == 'b' or t[j] == 'b':
                        cnt += 1
            if cnt == 2:
                ok = True

Feel free to share your approach, if it was somewhat different.

Time Complexity

$O(|S| * |S|)$ per test case.

Space Complexity

$O(|S|)$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

SHKNUM - Video Editorial (C++, Java, Python)


GCDMOD - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Bhuvnesh Jain

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

EASY-MEDIUM

Prerequisites

GCD, Modular Exponentiation, Overflow-handling

Problem

Find the GCD of $A^N + B^N$ and $(A - B)$ modulo $1000000007$.

Explanation

The only property required to solve the complete problem is $GCD(U, V) = GCD(U % V, V)$. If you are unfamiliar with this, you can see the proof here.

Now the problem remains finding the value of $(A^N + B^N) % (A - B)$. This is can be easily done using modular exponentiation in $O(\log{N})$ complexity. You can read about on wikipedia and implementation at Geeks for Geeks.

With the above 2 things, you are almost close to the full solution. The only thing left now is to handle overflows in languages like C++ and Java. First, understand why we might get overflow and then how we handle it.

Note that we are computing $A^N % (A - B)$. Since, $(A - B)$ can be of the order ${10}^{12}$, the intermediate multiplications during exponentiation can be of the order of ${10}^{12} * {10}^{12} = {10}^{24}$ which is too large to fit in long long data type. Due, to overflows, you will get the wrong answer. To deal with overflows, below are 3 different methods:

  • Using "int_128" inbuilt datatype in C++. For details, you can refer to [mgch solution].

This approach has a complexity of $O(1)$.

  • Using an idea similar to modular exponentiation. Instead of carrying out multiplication operations, we use addition operations. Below is a pseudo-code for it:

    # Returns (a * b) % m
    def mul_mod(a, b, m):
        x = 0, y = a
        while b > 0:
            if b & 1:
                # No overflows in additons.
                x = (x + y) % m
            y = (y + y) % m
            b >>= 1
        return x

This approach has a complexity of $O(\log{B})$.

  • Using idea similar to karatsuba trick. This is specific only to this question as constraints are upto ${10}^{12}$ and not ${10}^{18}$. We can split $a$ as $a_1 * {10}^{6} + a_2$ and $b$ as $b_1 * {10}^{6} + b_2$. Note that all $a_1, b_1, a_2, b_2$ are now less than or equal to ${10}^{6}$. Now we multiply both of them and there will be no overflow now in intermediate multiplications as the maxmium value can be ${10}^{12} * max(a_1, b_1) = {10}^{18}$. The setter code using this approach.

The time complexity of this approach is $O(1)$.

The final corner case to solve the problem is the case when $A = B$. This is because calculating $A^N + B^N % (A - B)$, would lead to runtime error while calculating modulo $0$. For this case, we use the fact that $GCD(U, 0) = U$. Thus the answer is simply $A^N + B^N$.

The last part is just printing the answer modulo $1000000007$.

The overall time complexity is $O(\log{N} + \log{max(A, B)})$. The first is for calculating the modular exponentiation and the second part is for calculating GCD. The space complexity is $O(1)$.

Once, you are clear with the above idea, you can see the author implementation below for help.

Note that since the number of test cases was small, another approach which iterates over divisors of $(A - B)$ to find the answer will also pass within the time limit if proper care is taken of overflows and the case $A = B$.

Feel free to share your approach as well, if it was somewhat different.

Time Complexity

$O(\log{N} + \log{max(A, B)})$

Space Complexity

$O(1)$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

mgch's solution can be found here.

GCDMODE video editorial

$
0
0

Someone has uploaded video editorial for GCDMOD problem , i thought to share with you. GCDMOD

LONCYC - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Noszály Áron

Tester:Mark Mikhno

Editorialist:Bhuvnesh Jain

Difficulty

MEDIUM

Prerequisites

DFS, Cycle detection, case analysis.

Problem

You are given a simple graph with $N$ vertices and $M$ edges. Each vertex of the graph can belong to at most one cycle only. For every edge, you need to find the number of simple paths which contain this edge and contain at most one cycle edge in them.

Explanation

The editorial will mainly contain the case analysis through various images and will describe the approach in brief. The exact implementation details can be referred through the editorialist solution which is commented to explain the details in an editorial.

The first thing to do in the problem is to first identify cycle vertices and cycle edges. This is can be simply through DFS or BFS. If you are not aware of this, I recommend you to read through it here. For detailed explanation, Cormen has a very good explanation of it using the concept of back edges and color the vertices into 3 parts white (non-visited), gray (partially-visited) and black (completely visited). If you still have doubts about that, you can ask below. The sample graph which covers all possible corner cases used to describe the editorial is given below.

Now, we run a DFS where we try to split the graph into various trees. The different trees are connected through edges which are part of some cycle in the graph. This means while constructing the tree we will never traverse a cycle edge. At the same time, we will root the all such trees along some vertex and also calculate the subtree size for every vertex as well. The below image shows the output of the algorithm. (This is done as part of $dfs$ function in the implementation). The root of the tree is marked in blacked colour and underlined.

Now, we have 2 cases:

  • CYCLE EDGE

Consider the case for edge $(8, 9)$. Since one cycle edge is already included, it means we can only add paths which do not include cycle edges. This is exactly we tried to calculate in the DFS above. So, we basically find the number of vertices (or paths as it is a tree) for both end vertices $8$ and $9$. The answer is simply the product of these $2$ values as it means we chose endpoint from the vertex in tree same as $8$ and another end from tree same as $9$.

  • NON-CYCLE_EDGE

Consider the case for edge $(12, 15)$. We split the answer into two parts: one containing no cycle edge and other containing one cycle edge. For the first case, we simply use the DFS done before. The vertices for starting and ending parts are highlighted in different colours. The answer is simply the product of the number of ways of choosing starting and ending vertices.

Now for the case when the path contains exactly one edge from a cycle, we again have 2 options. The cycle edge comes from the vertex $12$ or from vertex $15$. The first case is highlighted in the left image while the second case is highlighted in the right image.

Below figures also highlight how the calculation is done for other non-cycle edges like $(1, 8)$ and $(1, 3)$.

Edge $(1, 8)$. No-cycle path:

Cycle-edge paths (Left: containing cycle as part of vertex $1$, Right: containing cycle as part of vertex $8$)

Edge $(1, 3)$. No-cycle path:

Cycle-edge paths (Left: containing cycle as part of vertex $1$, Right: containing cycle as part of vertex $3$)

The exact details of the above cases can be seen in editorialist implementation. The code is completely commented for your help and is in line with the editorial. The case analysis and what information you store in the nodes can differ and can vary across implementation as well.

Feel free to share your approach, if it was somewhat different.

Bonus Problem

The problem statement doesn't provide a limit on $M$, the number of edges. Can you find the upper limit in terms of $N$?

Time Complexity

$O(N + M)$ per test case.

Space Complexity

$O(N + M)$

SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

QM10P5A editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Chandan Boruah
Tester:Taranpreet Singh
Editorialist:TaranPreet Singh

DIFFICULTY:

Simple

PREREQUISITES:

Greedy

PROBLEM:

Given N balls, each ball colored either red or blue, we have to find maximum number of green balls we can make. A Green ball can be made by merging consecutive red and blue ball.

QUICK EXPLANATION

  • Final composition of balls would never have consecutive balls are red and blue, since we can always merge them to obtain one more green ball.
  • So, merging balls greedily would generate maximum number of green balls.

EXPLANATION

All we need to do is to merge red and blue ball whenever we find a pair of such balls. All we need to prove now is that this approach is optimal.

Consider example: RBRB

Here, if we choose to merge second and third ball, our final compostion would look something like this RGB. Since we cannot move Green ball from in-between, we cannot merge the remaining red and blue ball. This proves that we should perform the merge operation as early as possible, otherwise Green ball might block future merge operation.

Instead of pair (2, 3), had we chosen (1, 2), we can still merge (3, 4) getting 2 green balls in the end, thus, being the optimal approach for merging.

Complexity:
Time Complexity is O(N).

AUTHOR'S SOLUTIONS:

using System;
using System.Collections.Generic;
class some
{
    public static void Main()
    {
        int tests=int.Parse(Console.ReadLine());
        for(int k=0;k<tests;k++)
        {
            int t=int.Parse(Console.ReadLine());
            string s=Console.ReadLine();
            int max=0;
            int count=0;
            for(int i=0;i<t-1;)
            {
                if(s[i]!=s[i+1]){count++;i+=2;}
    else i++;
            }
            max=count;
            count=0;
            for(int i=1;i<t;)
            {
                if(s[i]!=s[i-1]){count++;i+=2;}
    else i++;
            }
            max=Math.Max(count,max);
            Console.WriteLine(max);
        }
    }
}

AUG18 - Problem Discussion

$
0
0

Hey guys!!

Finally after 10 tiring days the August long concludes. Lets share our approaches for the problems here while editorials for problems come out (at this moment not all of them are out)? Got any interesting approach which you cant wait to share? The wait is over :)

So, which was your favourite problem? I had best time solving Interactive Matrix :). The princess gave me a run for my score xD - so I let her stay with dragons and be by herself then :p

But on a serious note, anyone who was able to save the princess (or prince...? :p). I kept on getting WA for larger TCs, so I appreciate any approaches for it :)

Let the discussion begin!

Internal Server Error in LTIME62 Forced Particles question

$
0
0

@admin I have been trying to submit solution for this problem for the past one day, but every time I'm getting internal server error on the submission result page!

KCOMPRESS Last TC

$
0
0

Here is link of my solution to KCOMPRESS " https://www.codechef.com/viewsolution/19705500 ".

I am somewhere stucked with the last test case.

Can someone find the testcase against which my code is not working ?


How I solved GCDMOD

$
0
0

It took me days to come up with a solution to GCDMOD, so I wish to share it with people with the complete approach on how I did it.

Step 1: Choosing the algorithm to calculate gcd of two numbers

This was a crucial step, I was confused between using a library for big integers or something. But when the idea clicked, I found out that normal Euclidean GCD was enough (Note normal one, not extended one)

Step 2: Tweaking the algorithm

Now next step is to tweak the algorithm so that we can get out desired results. For this, we will use two properties from modular mathematics which are

$$ (a*b)\%m = (a\%m * b\%m)\%m $$

$$ (a*b)\%m = (a\%m + b\%m)\%m $$

Now we know that the first step of the Euclidean GCD algorithm is that we recall gcd(b%a, a).

Step 3: The remaining workout

Now let's solve the question for $A, B, N, $ and $ A \neq B $

As we discussed we will first step of the Euclidean algorithm will be

$$(A^N + B^N)\%(A-B)$$

$$ var = [(A^N)\%(A-B) + (B^N)\%(A-B)]\%(A-B)$$

Now $(A^N)\%(A-B)$ or $(B^N)\%(A-B)$ can be calculated using modular exponentiation

Now all left is to $var$ we calculated is within the range of long long int and now just have to calculate gcd with $(A-B)$

Step 4: Checking edge cases

In this approach, there is only one edge case that is $A = B$. When this happens, the answer is simple $2 \times(A^N \% 1000000007)$

Link to my solution

If you have any doubts or think I went wrong somewhere please do tell me. Hope this helps other coders.

KCOMPRESS August long challenge

Augus long challenge SPELLBOB

$
0
0

hi guys i need little help debugging my code to get the correct output..

import java.util.*;

public class Bob {

public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    int T, i = 0;
    T = input.nextInt();
    while (T-- > 0) {
        String A;
        String B;
        A = input.next();
        B = input.next();
        char[] str1 = A.toCharArray();
        char[] str2 = B.toCharArray();
        A=A.toLowerCase();
        B=B.toLowerCase();
        int l1 = A.length();
        int l2 = B.length();
        for(int j=0;j<str1.length||j<str2.length;j++) {
            if(str1[j]>='A'&& str1[j]<='Z')
                System.out.println("no");
            else if(str2[j]>='A'&& str2[j]<='Z')
                System.out.println("no");
        }
        if (l1 != 3 || l2 != 3)
            System.out.println("no");

        else if ((A.equals("bob") || A.equals("bbo") || A.equals("obb"))
                || (B.equals("bob") || B.equals("bbo") || B.equals("obb"))) {
            System.out.println("yes");
        }
        else {
            if (str2[i] == 'b' || str2[i] == 'o') {
                if (str1[i + 1] == 'b') {
                    if (str1[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str2[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str1[i + 2] == 'o')
                        System.out.println("yes");
                    else if (str2[i + 2] == 'o')
                        System.out.println("yes");
                    else
                        System.out.println("no");
                }
                else if (str2[i + 1] == 'b') {
                    if (str1[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str1[i + 2] == 'o')
                        System.out.println("yes");
                    else
                        System.out.println("no");
                }
                else if (str1[i + 1] == 'o') {
                    if (str1[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str2[i + 2] == 'b')
                        System.out.println("yes");
                }
                else if (str2[i + 1] == 'o') {
                    if (str1[i + 2] == 'b')
                        System.out.println("yes");
                    else
                        System.out.println("no");
                }
            }

            else if (str1[i] == 'b' || str1[i] == 'o') {
                if (str2[i + 1] == 'b') {
                    if (str2[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str1[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str2[i + 2] == 'o')
                        System.out.println("yes");
                    else if (str1[i + 2] == 'o')
                        System.out.println("yes");
                    else
                        System.out.println("no");
                }
                else if (str1[i + 1] == 'b') {
                    if (str2[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str2[i + 2] == 'o')
                        System.out.println("yes");
                    else
                        System.out.println("no");
                }
                else if (str2[i + 1] == 'o') {
                    if (str2[i + 2] == 'b')
                        System.out.println("yes");
                    else if (str1[i + 2] == 'b')
                        System.out.println("yes");
                }
                else if (str1[i + 1] == 'o') {
                    if (str2[i + 2] == 'b')
                        System.out.println("yes");
                    else
                        System.out.println("no");
                }
            }
        }
    }
}

}

July Lunchtime 2018 ratings not given.

$
0
0

The ratings for July Lunchtime 2018 are not included. It does not even show on my contest page although I participated in it.

Ratings not updated for PROCJ (rated for divison 2)

$
0
0

Why are ratings not updated for Pro Con Junior, rated for divison 2 held at 11 August, but ratings are updated for August Challenge 2018

Viewing all 40121 articles
Browse latest View live


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