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

[Coder's Calendar] Firefox and Chrome extension for Competitive Programming

$
0
0

Screenshot

Hi all,
We all know how difficult it is to be aware of the different coding competitions taking place on various websites,so I've made an add-on(extension) both in chrome and firefox to make this task easy.

  • Updates from Codechef,HackerEarth,Hackerrank,Topcoder,Codeforces
  • Add to google calendar feature.

Star the project in Github to show your support.
https://github.com/nishanthvijayan/CoderCalendar

Coder's Calendar is available for download at:

Found any bugs? Have any suggestions to make this project better? Know any other cool coding sites?
Do comment about it.
Happy Coding!

Preferences menu:


KSUBSUM - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

EASY

EXPLANATION

Given an array A of N integers, we are asked to find the Kth maximum sum of a contiguous subarray of elements. Finding the Maximum sum of a subarray is a well known problem. If the array elements are all non-negative, we can use binary search to find the answer in O(n log S) time, where S is the maximum sum of a subarray. In this problem, the values can be negative. As with the other problems in this set, look at the constraints carefully, N ≤ 10,000 and K ≤ 2012. We go through the array from left to right and at each index i, we find all K maximum sums of subarrays, ending at index i. If S is the prefix sum array, where S[i] = A[1] + A[2] + ... + A[i], then all subarray sums ending at index i can be computed using S[i] - S[j], for j = 0 to i-1 and considering S[0] = 0. But we only need top K of them, so we can subtract S[j] s in non-decreasing order and only K of them. This requires us to maintain the array S in sorted order and this can be done similar to insertion sort in O(K) time per insertion.

Now that we have the top-K subarray sums ending at index i, we can compare them with the current top-K best answers so far and pick some of them and drop others. Note that at each step you only need to maintain K minimum prefix sums and K maximum subarray sums so far. Given the best K sums so far and the current K sums, we can merge the two sorted arrays and get the updated best K sums. This can also be done in O(K) time. The overall time complexity is O(NK). Maintaining a set ( or heap ) in which each insertion is additional O(log K) only increases the running time by more than 10x and may not fit in the given time limit.

SETTER'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Can be found here.

PPTEST - Editorial

$
0
0

PROBLEM LINKS:

Practice
Contest

Author:Vitaliy Herasymiv
Tester:Tasnim Imran Sunny
Editorialist:Tuan Anh

DIFFICULTY:

Easy

PREREQUISITES:

Dynamic Programming

PROBLEM:

There are N questions. The ith question needs T[i] minutes to learn and will give you C[i] × P[i] points in the tests. You have W minutes to learn the questions. Your job is to find which questions to learn to maximise your score.

EXPLANATION:

We need to choose a sub-set of N questions so that the total learning time does not exceed W and the total socore is as large as possible. With the constraint N ≤ 100 we cannot try out all possible sub-sets since the number of sub-sets can be 2 100 which is extremely large.

We need to use dynamic programming in this problem. Let F[i][j] be the maximal score you can get if you spend no more than j minutes to learn some questions amongst the first i questions. Now, there are two cases:

  • If you choose to learn the ith question then you get maximally F[i - 1][j - T[i]] + C[i] × P[i] points. Be careful with the case where j < T[i].
  • If you do not learn the ith question then you get maximally F[i-1][j] points.
The complexity of this solution is O(N×W). For the initialization you need to set F[0][j] = 0 for all0 ≤ j ≤ W.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

In the solution of problem setter and the tester an optimization is used to reduce the memory complexity. With a little modification of the algorithm above we can solve this problem using a one-dimensional array of W elements. The pseudo code is given below:

    FOR i -> 0 to W
        G[i] = 0
    ENDFOR

    (*)FOR i -> 1 to N
        FOR j -> W downto 0
            G[j] = max(G[j + T[i]], G[j] + C[i] × P[i])
    ENDFOR

After the ithiteration of the for loop (*), the value in G array is exactly as in the ith row of the F array in the original algorithm. Notice that in the second For loop we need to consider the value of j in the decreasing order so that each time we use G[j] to update G[j + T[i]] we know that the value in G[j] is the optimized value of using j minutes and the first (i - 1) questions only.

COMM3 - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

EASY

EXPLANATION

Try all 3 pairs of transceivers to see which ones can communicate directly. If at least 2 pairs can communicate directly then at least one transceiver can communicate directly with the other two so the answer is 'yes'. Otherwise, if at most 1 pair can communicate directly then the answer is 'no'. To determine if two transceivers located at (x1,y1) and (x2,y2) we simply check that (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2) < = r * r. This is the same as checking that the distance between them is r, but we can avoid floating point computations this way. Note that the input numbers are small enough to ensure that the above expression only involves signed 32 bit integers.

SETTER'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Can be found here.

How to find NZEC error ??

$
0
0

Hi! please tell me what is NZEC error, how to find it inside the code and how to prevent it ? How do codechef encounter NZEC errors, do they use any software ??

SHUFFLE2 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Sergey Kulik
Tester:Suhash Venkatesh and Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

Splay trees, permutations, chinese remainder theorem

PROBLEM:

A deck of $N$ cards is shuffled using overhand shuffle. Specifically, the shuffle consists of $M$ cuts repeated $Q$ times, where in the $i$th cut the cards from position $L_i$ to $R_i$ are moved to the beginning.

You have to answer two kinds of questions:

  • Given $Q$, what is the final order in which the cards appear in the end?
  • Given a final order, compute the smallest $Q$ for that order to occur? (it's guaranteed that this $Q$ exists)

QUICK EXPLANATION:

The first part of the problem is to compute the permutation after performing the $M$ cuts once. Each cut $[L_i,R_i]$, $1 \le L_i \le R_i \le N$, can be decomposed into a series of prefix reversals:

  • Reverse $[1,L_i-1]$
  • Reverse $[1,R_i]$
  • Reverse $[1,R_i-L_i+1]$

Prefix reversals can be done efficiently using splay trees with lazy propagation. First, we create a balanced splay tree, where each node holds the size of the interval it represents and a lazy boolean attribute called reverse, which tells whether the interval under this node must be reversed completely. To visit a node means to propagate its reverse attribute downward, i.e. if reverse is true, swap the children and flip their reverse attributes. Now, to reverse a prefix $[1,x]$:

  • If $x = 1$, nothing needs to be done :)
  • If $x = N$, then just flip the reverse attribute of the root, and visit it.
  • Otherwise, splay on the $x + 1$th node in the inorder traversal (this node can be found efficiently using the size attributes). While traversing the path, don't forget to visit each node! After the splay, this node is now the root, and its left child contains exactly $x$ nodes, which is the exact interval we want. So just flip the reverse attribute of the left child of the root :)

This can be performed in $O(N + M \log N)$ time.

The next step is to decompose the permutation into disjoint orbits, or cycles.

Next, let's answer the two questions:

  • Given $Q$, what is the final permutation? In other words, what is the $Q$th power of the given permutation? To do this, we simply raise each cycle to the power $Q$. Raising a cycle to any power requires only rotating the cycle a given number of times, which takes linear time in the size of the cycles. Therefore, this runs in $O(N)$ time.

  • Given the final permutation, what is $Q$? We can reverse-engineer the approach to the previous question. Given any cycle of size $S_i$, we check what happens to it in the final permutation and derive which $Q$s could have resulted in that outcome. You'll find that all such $Q$s satisfy a congruence relation $Q \equiv k_i \pmod{S_i}$ for some value $k_i$. For each cycle you have one congruence relation. Therefore, we can use the Chinese remainder theorem to derive a single congruence $Q \equiv k \pmod{S}$, for $0 \le k < S$ and $S$ is the order of the permutation. The minimum $Q$ is simply $Q = k$, and this also runs in $O(N)$ time.

Note that in the second question, the moduli are not necessarily pairwise coprime, so you may have to adjust your algorithm to combine two congruences.

EXPLANATION:

The more detailed explanation is being written. Stay tuned!

Time Complexity:

$O(N + M \log N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

To be uploaded soon.

PLANEDIV - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Maksym Bevza
Tester:Sergey Kulik
Editorialist:Kevin Atienza

PREREQUISITES:

Cartesian coordinates, parallel lines, sets, GCD, Euclidean algorithm, sorting

PROBLEM:

A set of lines is called perfect if there's no point that belongs to two distinct lines of the set.

Given a set of $N$ lines, each determined by three coefficients $(A,B,C)$ (representing the line $Ax + By + C = 0$), what is the size of the largest perfect subset?

QUICK EXPLANATION:

The answer is simply the largest set of distinct lines that are all parallel to one another. To get the answer, group the lines according to slope, being careful to not count coinciding lines twice. (e.g. $x + y + 1 = 0$ coincides with $2x + 2y + 2 = 0$ so should only be counted once.) The answer is the size of the largest group.

One way to group the lines is to add them to a set data structure. Another is to sort them according to slope, so that lines with the same slope are found consecutively.

EXPLANATION:

A set containing just one line is clearly perfect, so let's investigate perfect sets of size at least two. Let $a$ and $b$ be two lines in a perfect set. Since $a$ and $b$ must not intersect (and definitely must not coincide), then they must be parallel. In other words, they must have the same slope. Since this argument applies to any pair of lines in the perfect set, we can say that a perfect set is just a set of distinct lines all having a common slope.

Our goal now is to find the largest perfect set. Naturally, we want to group the lines according to slope, and take the largest group as the answer. In fact, this is basically the algorithm to solve this problem! However, there are at least two problems that might come up when implementing this:

  • First, we must be able to represent the slope exactly, and not just a floating point number, otherwise you risk getting wrong answer due to bad rounding. (Remember that many numbers cannot be represented exactly in floating point.)
  • Second, we must be able to detect whether two lines coincide, because we should only count coinciding lines once.

We'll deal with these problems one by one.

Representing the slope

First, note that it's actually possible to get accepted while using floating point slopes (especially if the data isn't strong enough or the bounds of the problem prevents rounding errors from being a problem), but it's still important to know an error-free way to represent slopes, in other words, a way that can be shown to always work. Also, representing a slope exactly has many applications even outside of this problem. So how do we represent the slope of a line exactly?

Representation 1

Well, one way to represent the slope exactly is to simply represent it as an exact fraction. For example, the slope of $Ax + By + C = 0$ is $-A / B$. But we must be able to detect the same fractions! (For example, $1 / 2 = 2 / 4 = 3 / 6$.) One way to do it is to reduce the fraction to lowest terms, by dividing the numerator and denominator by the greatest common divisor (gcd). This works because rational numbers have a unique representation in lowest terms.

We need to represent negative slopes as well! To make the "lowest term representation" unique, simply ensure that the denominator is always positive. Another problem that will arise is how to represent the slope of vertical lines. Their slope can't be represented by a rational number (because it's "infinite"). However, since there is a unique slope for vertical lines, we can simply use a unique object to represent the "vertical slope". (or just handle vertical lines separately)

Representation 2

There's actually a way to represent the slopes without needing any special handling for the vertical slope. Instead of representing the slope of the line as a rational number, we represent it as the vector pointing to the direction of the line. Remember that a vector is an ordered pair $\langle x, y \rangle$, which represents the direction pointing from $(0,0)$ towards $(x,y)$. (In a vector, the distance between these points are also important, but since we're only talking about the "direction" of the line, it doesn't matter for our purposes.)

What is the direction vector of the line $Ax + By + C = 0$? Suppose $(x_1,y_1)$ and $(x_2,y_2)$ are points on this line. Then $\langle x_d, y_d \rangle = \langle x_2-x_1, y_2-y_1\rangle$ is one possible direction vector. But these points satisfy the equation of the line, so: $$Ax_1 + By_1 + C = 0$$ $$Ax_2 + By_2 + C = 0$$ Subtracting these two, we get: $$A(x_2-x_1) + B(y_2-y_1) = 0$$ or $$Ax_d + By_d = 0$$ But one solution to this equation is simply $x_d = B$ and $y_d = -A$, thus $\langle B, -A \rangle$ is one direction vector for the line $Ax + By + C = 0$!

But in order to group our lines according to slope, we must again be able to detect vectors representing the same direction. Similarly to rational numbers, we must find some sort of "normal form" that we can reduce our direction vectors to. Note that we also consider opposing vectors as representing the same "direction", e.g. $\langle x, y \rangle$ and $\langle -x, -y \rangle$.

One way to define such a normal form is the following. Let's say a vector $\langle x, y \rangle$ with integer coordinates is in normal form if and only if $x$ and $y$ are relatively prime and the polar angle of $(x,y)$ is less than 180 degrees. The reader is invited to prove that every direction vector has a unique normal form.

Finally, to convert $\langle x, y \rangle$ to normal form, simply divide both coordinates by $\gcd(x,y)$, and then negate both if $y$ is negative, or $y = 0$ and $x$ is negative.

Using vectors instead of slopes, we don't have to worry about "infinite" slopes any more!

Detecting coinciding lines

Next, what about detecting coinciding lines? Note that coinciding lines necessarily have the same slope, so we can simply look at lines with the same slope, and find among those the lines that overlap.

Note that two lines overlap if and only if their equations are the same, up to a nonzero multiplicative constant. For example, the following lines all coincide with one another:
$$4x + 6y + 1 = 0$$ $$8x + 12y + 2 = 0$$ $$44x + 66y + 22 = 0$$ $$-44x - 66y - 22 = 0$$ However, these lines do not coincide with the line $4x + 6y + 2 = 0$ or $4x + 6y - 1 = 0$.

In this case, we can simply try to reduce the equations into some sort of "normal form" (as in the previous section), in such a way that each equation of a line has a unique normal form. Here's one way: Let's say the equation $Ax + By + C = 0$ is in normal form if $A$, $B$ and $C$ are relatively prime, and one of the following conditions hold:

  • $C > 0$
  • $C = 0$ and $B > 0$
  • $C = 0$, $B = 0$ and $A > 0$

The idea behind this is actually just an extension of our "normal form" of direction vectors in the previous section, because $\langle x, y \rangle$ is in normal form if $x$ and $y$ are relatively prime and one of the following conditions is satisfied:

  • $y > 0$
  • $y = 0$ and $x > 0$

Thus, we can just reduce all our equations to their normal forms, and this way, two lines coincide if and only if their equations are equal!

Solution

Armed with the above techniques, the solution is now easy. First, group the lines according to their slopes (or normal forms of their direction vectors). Then, for each group, compute the normal forms of their equations, and remove duplicates. Finally, the answer is simply the largest remaining group!

The following is a Python implementation which solves a single test case:

from fractions import gcd
from collections import defaultdict
s = defaultdict(set)
for i in xrange(input()):
    a, b, c = map(int, raw_input().strip().split())
    g = gcd(a, b)
    h = gcd(g, c)
    s[a/g, b/g].add((a/h, b/h, c/h))
print max(map(len, s.values()))

Since Python's $\text{gcd}(a,b)$ is guaranteed to have the same sign as $b$, dividing by the gcd will already guarantee normality (as we've defined it).

The time complexity of this algorithm is $O(N \log N)$ if one uses balanced tree sets.

Alternatively, you can just sort them according to their normal forms, so parallel lines and coinciding lines are found consecutively. This runs in $O(N \log N)$ time also.

Time Complexity:

$O(N \log N)$ or expected $O(N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter
Tester
Editorialist

CHRL1 - Editorial

$
0
0

PROBLEM LINKS

Contest
Practice

Author: Roman Furko
Tester: Sergey Kulik
Editorialist: Praveen Reddy Vaka

DIFFICULTY:

cakewalk

PREREQUISITES:

Basic Combinatorics, Enumerating/Iterating over combinations

Hint: Consider all possible combinations of choosing oranges and see what you can do with them.

EXPLANATION

subtask1: The weight for each orange is given to be 1.
To pick the oranges such that we get a maximum weight purchase is the same as picking the most number of oranges. This can solved by a simple greedy approach. Just sort the array of costs in increasing order. Traverse the array from left to right and see how many oranges can you buy using the k rubles that you have. The answer will be the number of oranges that you can get.

subtask2: n = 5
Given five oranges you can choose your oranges from one of the following 31 ways (Consider a string of “abcde” of length 5, each character can be 0 or 1. If ith character is 1 we take ith orange otherwise we don’t.)

C(5, 1) = 5 possible combinations of choosing exactly one orange.
["00001", "00010", "00100", "01000", "10000"]
C(5, 2) = 10 possible combinations of choosing exactly two oranges.
["00011", "00101", "00110", "01001", "01010", "01100", "10001", "10010", "10100", "11000"]
C(5, 3) = 10 possible combinations of choosing exactly three oranges.
["00111", "01011", "01101", "01110", "10011", "10101", "10110", "11001", "11010", "11100"]
C(5, 4) = 10 possible combinations of choosing exactly four oranges.
["01111", "10111", "11011", "11101", "11110"]
C(5, 5) = 10 possible combinations of choosing exactly five oranges.
["11111"]

Just go through all possible combinations and among the combinations which have a cost less than equal to k rubles pick the one yielding the maximum weight. You can hardcode the previous combinations but computing them by hand may be very tedious so it is not recommended unless you get it is more clever way like copying them from some other source on the internet. We will now see a way of doing this using code. Consider the following code.

for (i = 1; i <= 5; i++) {
    //take ith orange
    for (j = i+1; j <= 5; j++) {
        //take ith, jth orange
    }
}

In the outer for loop you can select exactly one of the oranges 1,2,3,4 and 5. In the inner for loop you can select all possible ways of choosing 2 oranges (1, 2), (1, 3), (1, 4), (1,5), (2, 3), (2,4), (2,5), (3,4), (3,5),(5,5). Using more for loops you can get a way to select all possible ways of 3 oranges, 4 oranges, 5 oranges. Every time you select a subset of oranges just see if they don’t cost more than k rubles and among all such possible subsets pick the one with the maximum weight. Refer to editorialist’s solution for an implementation of this.

subtask3: (solves subtask2 and subtask1 as well)
We will select all possible combinations of choosing from the n oranges and among whichever combinations cost us no more than k rubles we pick the one with the maximum weight. The number of different ways of choosing oranges from the given oranges is same as the number of subsets of a set which is 2^n (this includes a way of selecting no orange as well). Since n is at max 10 we are looking at a maximum of 2^10 = 1024 combinations, so the problem is easily solvable this way. You can solve this in multiple ways.

Method 1:
You can iterate through all the subsets of the n oranges by using simple bit level operations. Read through the tutorials at http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=bitManipulation and http://www.codechef.com/wiki/tutorial-bitwise-operations. You can see the tester’s code for an implementation of this mechanism. This is the usual expected and recommended way of doing this kind of a thing in contests.

Method 2:
You could precompute all possible subsets in the following way. We will use string representation used in subtask2. We use a string S of length n to represent a subset, if ith position is 1 we select ith orange otherwise we don’t.

Have a two dimensional array combinations11 (Since n <= 10)

combinations[i][j] holds a list of all strings denoting the ways of selecting j oranges from a total of i oranges. (j can’t be greater than i)

We will initialize combinations[0][0] with a list having just the empty string. We will initialize combinations[i][0] with a list having just a string of length i made up of all 0’s.

We can compute combinations[i][j] recursively as follows. We want to generate all i length strings having exactly j bits set to 1. We can set 1st bit to either 1 or 0. In the first case we can add 1 in front of the list of all strings of combinations[i-1][j-1]. In the second case we can add 0 in front of all the strings of combinations[i-1][j] (only if i-1 >= j otherwise this would lead to absurdity). These are the only possible strings of length i and having j bits set. So we can add all these strings to a new list and set them to combinations[i][j].

We can compute the whole combinations array either recursively or iteratively. Refer to editorialist’s solution to look at a way of generating this iteratively.

Once we have this generated for a given n . We look at all the strings in the lists combinations[n][1], combinations[n][2], ….., combinations[n][n] and for each string we see the oranges that are to be selected and compute our maximum weight needed.

Method 3: Since n can be at max 10 we can simply use 10 for loops just like the 5 for loops used in subtask2. Given the nature of for loops conditions if there is anything to be selected it will be executed otherwise the for loop condition fails in the initial check it self, so the previous method just works seamlessly in this case. Refer to the method subtask3_forloops in editorialist’s solution. This is a bit ugly solution and has a chance of some typos getting in when dealing with so many loop variables. If you are a beginner this might seem the simplest of all three solutions but on greater practice you will realize that the method 1 is in fact the simplest solution to implement in this case.

If you are using a language like python which has in built functions to generate combinations your task becomes very easy. See the editorials python solution. Note that currently python is not a supported language in either IOI or ICPC, but it is supported on all major online judges.

Note: This problem looks like a standard knapsack but the DP solution for knapsack for this problem would get a Time Limit Exceeded or Memory Limit Exceeded message because of cost being as big as 10^8.

SOLUTIONS

Setter's Solution: CHRL1.cpp
Tester's Solution: CHRL1.cpp
Editorialist's Solution: CHRL1.javaCHRL1.py


IOIPRAC INOI15 : Special Sums Solution WA ???

$
0
0

I came up with The following approach.

  1. for i == j, take max element from input
  2. for i < j , for ssum[i,j] = $ a_i + a_j + b_(i+1)+.....+b_(j-1) = (a_i + b1+.....+b_(j-1)) - ( b_1 +.....+ b_(i) - a_j) $

Find MAX of first contiguous element and MIN of second and Get The max sum using modified Kadane's Algorithm ..

  1. For i > j : Find the MAX Prefix and lowest index where it ends and MAX Suffix and highest index where it starts .... Run a loop and find max ( max prefix + highest suffix index with max sum after max prefix , max suffix with lowest index before max suffix ) ...

It works for some inputs but fails or SIGABRTS FOR OTHERS !http://ideone.com/hV7MbL

HISPDNET TLE and 1 test case WA

How to get started with the problems on grid walk?

$
0
0

I am new to competitive programming, I started solving the questions from the easy sections(From maximum number of submissions). I solved some of the questions but I always get stuck into the problems of grid walking, I always end up giving up on them. How do I get familiar with such problems.

And please refer me to some good and basic problems on grid walking, and also some source to form the base to solve such problems.

Thanks in advance.

ANUUND - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Anudeep Nekkanti
Tester:Gerald Agapov
Editorialist:Praveen Dhinwa

DIFFICULTY:

EASY

PREREQUISITES:

AD-HOC, sorting

PROBLEM:

Given an array A. Rearrange the array in such a way that A[1] <= A[2] but A[2] >= A[3] and A[3] <= A[4] upto A[N-1] <>= A[N] (depending on the parity of N) is satisfied. More Formally,
A[i] <= A[i + 1] if i is odd. A[i] >= A[i + 1] if i is even.

QUICK EXPLANATION

  1. O(N logN) Solution: Sort the array A. Pick A[1], then pick A[N - 1], A[2], A[N - 2] etc upto Nth element.
  2. O(N) Solution: Go from A[1] to A[N] in left to right order, if at any point of time, condition of given inequalities are not satisfied, then swap the elements in such a way that the condition is satisfied. We will prove in next section why this approach will always work.

EXPLANATION

O(N logN) Solution:

First step is to sort the array A. Now we have to build an array B such that it contains the elements of A in rearranged way. They B array is our answer to the given problem. We will first add A[1] in B, then A[N - 1], then A[2], A[N - 2], A[3], A[N - 3] etc. Note that this approach is always going to produce correct result because at the current step we are always picking the smallest and largest possible numbers which we can still pick, hence the inequality conditions given in the problem are never violated.

Sample Execution:
Let A = [4, 3, 5, 1].
Sort the array A.
A now becomes = [1, 3, 4, 5].
Our array B will be [1, 5, 3, 4].

Complexity: O(N log N).
All we need to do is to sorting of an array, All other operation costs only O(N) time. Hence time complexity is O(N log N).


O(N) Solution

We will go from left to right from A[1] to A[N]. If at any position, our inequality condition is unsatisfied, we will make a swap of i and i + 1 entries.

Sample Execution:
Let A = [4, 3, 5, 1, 2].
If we are first element (i = 1): A[1] <= A[2] is not satisfied, so we will swap A[1] and A[2].
So A will now become: [3, 4, 5, 1, 2]
Now we are at second element (i = 2): A[2] >= A[3] is not satisfied, so we will swap A[2] and A[3].
So A will now become: [3, 5, 4, 1, 2]
Now we are at third element (i = 3): A[3] <= A[4] is not satisfied, so we will swap A[3] and A[4].
So A will now become: [3, 5, 1, 4, 2]
Now we are at fourth element (i = 4): A[4] >= A[5] is satisfied, so we dont need to swap.
So A will remain as it is: [3, 5, 1, 4, 2]

Proof Of Correctness:
Assume that a, b, c, be the leftmost(Ordered from A[1] to A[N], A[1] is leftmost, A[N] is rightmost) elements of the array A for which condition is not satisfied. Let us assume that a be the elements which just precedes b. (ie order of occurrence of elements is a, b, c)
Let us suppose we want b >= c. (a <= b).
According to our assumption, a <= b is already satisfied, but b >= c is not satisfied (ie b < c)
Now on swapping b and c, our new order of elements will be a, c, b.
Note that now in this order a <= c(because a <= b < c).
and we have c >= b. (because c > b).

We can handle the second case in the exactly similar way too (Case when a >= b is satisfied but b <= c is not satisfied). This case is left for readers to prove.

Complexity: O(N):
For each index i from 1 to N, we can make at most 1 swap, Swap operation is constant operation, Hence we will only make total O(N) operations.

AUTHOR'S, TESTER'S AND EDITORIALIST's SOLUTIONS:

Author's solution
Tester's solution
Editorialists's solution

Weak test cases of January 2016 Long Challenge problem CBALLS

$
0
0

I have two submissions which give different output for same input and both are accepted.

INOI Problem Help

$
0
0

I was the solving the INOI problem free ticket. When I submit it, it gives wrong answer for larger values and correct answer for smaller values. I am unable to figure out why. Can anyone help me figure out. Here is my code.

http://ideone.com/e.js/LeqzkY

ABROADS - Editorial

$
0
0

Problem Link:

Practice
Contest

Difficulty:

Medium

Pre-requisites:

Disjoint Set Union

Problem:

Maintain the size of the most populated region after each query.

Explanation:

Solution for the subtask 1 (21 points):

The solution of this subtask is to use breadth first search after applying each query to find all the regions' city sets. If we have all the regions' cities sets, we can easily find the maximal populated region.

Let's describe this approach in more details.

Let's denote:

1) Integer array $P$, where $P[i]$ is the population of city numbered the $i$th.

2) Boolean array $D$, where $D[j]$ is true, if the road numbered the $j$th has been destroyed, and false otherwise.

3) Adjacency list $Adj$. We can store this list efficiently, for example, using STL vector in C++. For every adjacent node, let's store a structure, containing the following fields:

  • The number of the adjacent node, denoted by $node$.
  • The ID of the corresponding edge, denoted by $edge$.

Having all this, we can process the queries in the following way:

  • P $x$ $y$ - change the population of the city numbered the $x$th to $y$. In this case, we just make a single assignment: $P[x]$ = $y$. This operation is performed in $O(1)$.

  • D $x$ - destroy the road numbered the $x$th. Again, this is just a single assignment ($D[x]$ = true), so it is also performed in $O(1)$.

Now, how to find the size of the maximal populated region.

We will make use of queue data structure.

Let's iterate through all the nodes. Whenever we find a node which was not included in any connected component, we start the breadth first search. Let's describe it in brief:

  • Add the first node of the region to the queue.
  • While the queue is not empty, pick the node from the head of the queue and add all its' not yet added neighbors.

Let's denote Boolean array $Used$, where $Used[i]$ is true, if $i$th city was added to queue, and false otherwise.

The pseudocode of the algorithm for finding the size of the most populated region is given below.

ans = 0; For i := 1 to N used[i] = false For i := 1 to N if not used[i] queue.add(i); population = 0; while queue is not empty do curNode = queue.pop(); population += P[curNode]; For j := 0 to Adj[curNode].Length if ((not D[Adj[curNode][j].edge]) and (not Used[Adj[curNode][j].node])) Used[Adj[curNode][j].node] = true; queue.add[Adj[curNode][j].node]; ans = Max(ans, population); return ans

The complexity is $O(Q*(N+M))$.

Solution for all subtasks:

We will use the data structure called Disjoint Set Union.

Let's have $N$ elements numbered $1$ to $N$ and $N$ sets. Initially, the $i$th set contains the $i$th element.

Disjoint Set Union maintains two basic operations:

1) Uniting two sets.

2) Finding the set containing the given element.

The amortized time per operation is $O(\alpha(N))$, where $\alpha(N)$ is less than $5$ for all remotely practical values of $N$.

Note that you don't have to output the size of the most populated region before reading the next query. So, you can read all the queries in advance and solve the task in reverse order.

Assume that all $Q$ queries were performed. Let's add all connected components (regions) to the DSU. Obviously, we can determine the most populated region.

Let's create the DSU with $N$ elements denoting the cities and $N$ sets denoting the regions. Along with each set (say, the $X$th), let's maintain the value of $P[X]$, denoting the total population of the cities in the $X$th set. Now, the DSU corresponds to the road system with $N$ cities, given populations and without roads. Note that we should take the populations that are obtained after the performing of all the queries.

Now, assume that all the queries has already been performed. Then, there is a set of roads, which has not been deleted. Let's add all of them. The addition of the road is simply merging two corresponding sets in the DSU structure. Since we have one non-standard operation here, namely, handling the sizes of the regions, letТs give a pseudocode for it.

Given that we need to add a road connecting the city numbered the $X$th and the city numbered the $Y$th.

Merge (X, Y) setX = FindSet(X) setY = FindSet(Y) if (setX == setY) return; SetParent(setY, setX) P[setX] = P[setX] + P[setY]

Now, let's "rollback" the queries starting with the last one. The "rollback" of the change population query is changing the value of the corresponding $P[X]$, and the "rollback" of the road deletion query is adding the road like we've described above.

Meanwhile, we can also maintain a priority queue of an STL set for determining the size of the largest region quickly. This way, we can answer on the maximal region population in $O(\log N)$.

The complexity is O($N + M \alpha(N) + Q \log N$).

Setter's Solution:

Can be found here

Tester's Solution:

Can be found here


Getting Wrong answer in POWERUP spoj "http://www.spoj.com/problems/POWERUP/"

$
0
0

My code is http://ideone.com/UzuqBL but i am continously getting wrong answer please help me to find out where i am doing wrong or missing some corner case.

CHEFST - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Tapas Jain
Tester:Sergey Kulik
Editorialist:Kevin Atienza

PREREQUISITES:

Arithmetic series, greedy, ad hoc

PROBLEM:

Consider a single-player game on two piles of stones. One has $n_1$ stones and the other has $n_2$ stones. Before the start of the game, we choose an integer $m$.

In a move, we choose a number between $1$ and $m$, and remove that number of stones from both piles. (this is only possible when both the piles have at least that many stones). Also, the number of stones to remove at each step must be unique. The game ends when there are no more moves.

What is the minimum number of stones that could remain, among all possible games?

QUICK EXPLANATION:

The answer is $n_1 + n_2 - 2x$, where $x$ is the maximum number of stones we can remove from both piles.

We can only remove up to $1 + 2 + \cdots + m = \frac{m(m+1)}{2}$ stones from both piles. If $n_1$ and $n_2$ are both at least $\frac{m(m+1)}{2}$, then this is the maximum number we can remove. Otherwise, we can remove up to $\min(n_1,n_2)$ from both piles. Therefore, $x = \min(\frac{m(m+1)}{2}, n_1, n_2)$.

The answer can also be expressed as a single expression: $$\max(n_1 + n_2 - m(m+1), n_1 - n_2, n_2 - n_1)$$

EXPLANATION:

At any point in the game, the number of stones we have removed from both piles are always equal. Suppose we remove $x$ stones from both piles. Then there are $n_1 - x$ stones remaining in the first pile and $n_2 - x$ in the second. Therefore, the number of stones remaining is: $$(n_1 - x) + (n_2 - x) = n_1 + n_2 - 2x$$ The answer is the minimum value of this expression. $n_1$ and $n_2$ are fixed throughout the game, but we can control $x$ depending on how we play. But a higher $x$ corresponds to a lower $n_1 + n_2 - 2x$, so we actually want to maximize $x$, the number of stones we remove from both piles!

Maximum number of removed stones

Next, let's consider the requirement that "the number of stones to remove at each step must be unique". What does this mean for us? Well, since there are only $m$ unique numbers from $1$ to $m$, namely $1, 2, \ldots, m$, this means that the game ends after at most $m$ moves, and that the maximum number of stones we can remove is simply: $$1 + 2 + 3 + 4 + \cdots + m$$ This is actually a pretty famous sum, and the formula is $\frac{m(m+1)}{2}$. (A derivation is given in the appendix.) Therefore, we can only remove between $0$ to $\frac{m(m+1)}{2}$ stones.

Removing a given number of stones

Now we know that we can only remove between $0$ to $\frac{m(m+1)}{2}$ stones. The next question is: given some number $r$ between $0$ and $\frac{m(m+1)}{2}$, can we remove exactly $r$ stones? In other words, is it possible to express $r$ as a sum of distinct numbers from $1$ to $m$? For example, can you try to express the number $31$ as the sum of distinct numbers from $1$ to $10$?

Let's try. Since $31$ is huge, we try adding the large addends first. Say $10$. Then $31 - 10 = 21$ remains. The next largest addend is $9$, so we try that. $21 - 9 = 12$ remains. The next one is $8$, so we try that, and $12 - 8 = 4$ remains. Our number is small now, and in fact since it's already $\le 7$, we can just use $4$ as our final addend. Therefore: $$31 = 10 + 9 + 8 + 4$$ Does this greedy algorithm always work? Amazingly, yes! (as shown in the appendix) Therefore, given any $r$, we can always remove exactly $r$ stones.

Maximizing the number of removed stones

We're almost there! We want to maximize the number of stones to remove. Clearly, regardless of the size of the piles, the absolute maximum number we can remove is $\frac{m(m+1)}{2}$ as shown above. Thus, if $n_1$ and $n_2$ are both at least $\frac{m(m+1)}{2}$, then this is the maximum.

Now, what if one of $n_1$ and $n_2$ are smaller than $\frac{m(m+1)}{2}$? In other words, $\min(n_1,n_2) < \frac{m(m+1)}{2}$. In this case, we can no longer remove $\frac{m(m+1)}{2}$ stones, because there aren't enough stones in one of the piles. In fact, we can't remove more than $\min(n_1,n_2)$, because this is the size of the smaller pile. But since $\min(n_1,n_2)$ is smaller $\frac{m(m+1)}{2}$, as shown above we can always remove exactly $\min(n_1,n_2)$ stones. Therefore, the maximum stones we can remove is actually $\min(n_1,n_2)$!

We now have the whole solution! It is: $$n_1 + n_2 - 2x$$ where $$x = \min\left(\frac{m(m+1)}{2},n_1,n_2\right)$$

As a side note, we can actually substitute $x$ to $n_1 + n_2 - 2x$ to get the following expression: $$\max(n_1 + n_2 - m(m+1), n_1 - n_2, n_2 - n_1)$$ which gives us the following one-liner Python code (excluding the part of code that takes the input from stdin):

print max(n1 + n2 - m*(m+1), n1 - n2, n2 - n1)

Appendix: Showing that $1 + 2 + 3 + 4 + \cdots + m = \frac{m(m+1)}{2}$

We want to find a formula $S := 1 + 2 + 3 + 4 + \cdots + m$. I'll show a derivation here that is slightly different from the usual reverse and add method.

Let's begin: $$\begin{align*} S &= 1 + 2 + 3 + 4 + \cdots + m \\\ 2S &= 2 + 4 + 6 + 8 + \cdots + 2m \\\ 2S &= [1 + 3 + 5 + 7 + \cdots + (2m-1)] + \underbrace{1 + 1 + 1 + 1 + \cdots + 1}_{m} \\\ 2S &= [1 + 3 + 5 + 7 + \cdots + (2m-1)] + m \end{align*}$$ Now, consider the sum in the brackets. Notice the pattern: $$\begin{align*} 1 &= 1 \\\ 4 &= 1 + 3 \\\ 9 &= 1 + 3 + 5 \\\ 16 &= 1 + 3 + 5 + 7 \\\ 25 &= 1 + 3 + 5 + 7 + 9 \\\ 36 &= 1 + 3 + 5 + 7 + 9 + 11 \end{align*}$$ These are just the perfect squares! Thus, we conjecture that $1 + 3 + 5 + \cdots + (2m-1) = m^2$. In fact, this can easily be visualized as follows:

m=1  m=2    m=3      m=4        m=5
1    1 2    1 2 3    1 2 3 4    1 2 3 4 5
     2 2    2 2 3    2 2 3 4    2 2 3 4 5
            3 3 3    3 3 3 4    3 3 3 4 5
                     4 4 4 4    4 4 4 4 5
                                5 5 5 5 5

Note that the $m$th figure contains $m^2$ items, but at each step we're adding $1$, then $3$, then $5$, etc., items, to the previous figure!

Therefore: $$\begin{align*} 2S &= [1 + 3 + 5 + 7 + \cdots + (2m-1)] + m \\\ 2S &= m^2 + m \\\ S &= \frac{m(m+1)}{2} \end{align*}$$ which is what we wanted to show.

Appendix: Summing a number between $0$ and $\frac{m(m+1)}{2}$

Finally, we want to show why the greedy algorithm above works for expressing a number $r$ between $0$ and $\frac{m(m+1)}{2}$ as a sum of distinct numbers from the set $\{1, 2 \ldots m\}$.

The greedy algorithm first proceeds to check whether $m \le r$, and if so, adds $m$ to the list of addends. Then we proceed by expressing the number $r - m$ as a sum of numbers from the set $\{1, 2 \ldots m-1\}$. However, by assumption: $$1 + 2 + 3 + \cdots + m \ge r$$ By transposing the $m$, we get: $$1 + 2 + 3 + \cdots + (m-1) \ge r - m$$ Therefore, by doing an induction argument, we can see that the number $r - m$ can be expressed as a sum of numbers from the set $\{1, 2 \ldots m-1\}$!

This only works when $m \le r$ though. What if $m > r$? Then in that case, we can simply use $r$ as the lone addend in the sum, because $r \in \{1, 2 \ldots m\}$! Thus, we have just shown that the greedy algorithm works.

Time Complexity:

$O(1)$

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter
Tester
Editorialist

CHANGES IN CODECHEF SITE

$
0
0

Finally, the Old type of Codechef site is back. The colour on the question show that we have either solved the question fully, partially or whether it is wrong. The best thing is that the Announcements have been moved to the top of Contest page after the questions which makes it easy for us to see the changes. Also, the School label has been changed to Beginners which is a good move. Hope the contest ranking also appear soon on the contest page as well.

One more important notice for everyone. Almost most of us are aware that coding on ideone is not safe especially during the contests as our code can be easily seen (or hacked) by others and copied. This can lead to plagiarism and decrease in our rating points. I have been using Codechef IDE for about 3 months. It was a good experience. But now, it is even better. You can select the contest and the required problem. So, you can see the question and code on the same page. This think has been earlier used on Hackerrank and other sites. Happy that Codechef has also started it. For those, who have not installed any compiler and practice on ideone, I suggest them to use the Codechef IDE as well. Hope, you will also like it. You can also save your coding template in various languages on the IDE. So, when you login or start coding on the IDE, the template is available and use can easily just code out your logic. Also, it user friendly and has various options for changing the settings, downloading your code etc. The best is that your code is safe. No other user/person can view it until you submit the solution for your problem and the solutions are made public. GREAT WORK BY CODECHEF....

Thanks Codechef again for rolling back most of the changes. Hope that it stays forever..

Also, please post your comments regarding the new changes in the site. The best thing is Codechef is there to here you and serve you the best..

Happy Coding :)

FCTRL -Answer not getting accepted.

$
0
0

Despite having the correct logic I am not getting output? What am I doing wrong?

int main() { long long int count=0,i,T,n;
cin>>T;
while(T--)
{
cin>>n;
count=0;
for(i=5;n/i>=1;i=i*5)
{
count+=n/i;
}
cout<<count;
}
return 0;
}

SEADIV - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Sergey Nagin
Tester:Sergey Kulik
Editorialist:Kevin Atienza

PREREQUISITES:

Modular inverses, long division

PROBLEM:

Given two large numbers $A$ and $B$ in base 7, and $L$, compute $A / B \bmod 7^L$ (and write it also in base 7). It is guaranteed that $B$ is a divisor of $A$.

QUICK EXPLANATION:

Compute the digits of $C := A / B$ one by one, starting from the least significant. Each digit can be computed using inverses modulo $7$, based only on the last nonzero digits of $A$ and $B$, and once you extract each digit $k$ for a place value, say, $i$, then you need to subtract $B\cdot k7^i$ from $A$, in other words update $A := A - B\cdot k7^i$.

EXPLANATION:

At first glance, it seems the problem requires implementing some optimized arbitrary precision arithmetic code. One common way of doing general-purpose division of large numbers is to use Newton's method to compute to sufficient accuracy the inverse of the denominator using an iteration that uses only multiplication, and then multiplying it to the numerator. Multiplication can be done using standard techniques such as those based on fast Fourier transforms. However, these techniques are quite complex, and even if they might work, they're in fact quite overkill since there is a much simpler solution to the problem at hand. This solution works in our case because of the guarantee that $B$ is a divisor of $A$ which turns out to be quite significant.

In the following, please keep in mind that whenever we deal with $A$, $B$, $A/B$, and their digits, we're working in base 7. We also introduce the following notation: For a number $X$ in base $7$, let $X_i$ be its $i$th least significant digit (starting at $i = 0$). $X_i$ can be extracted as follows: $X_i = \lfloor X / 7^i \rfloor \bmod 7$.

Since $B$ divides $A$, let $C := A / B$ be their (integer) quotient (thus, $A = B\cdot C$). We want to know the last $L$ digits of $C$. Suppose we want to know just the last digit of $C$ (denoted $C_0$). What can we say about it? Well, we know that $A = B\cdot C$, so it must be the case that the last digit of $B$ multiplied by the last digit of $C$ is equal to the last digit of $A$, modulo $7$. In other words: $$A_0 \equiv B_0\cdot C_0 \pmod{7}$$ This is similar to the fact that, for instance, in base 10, the product of any number ending $6$ and another number ending in $9$ always ends in $4$, which is equivalent to $6\cdot 9\bmod 10$.

What's nice about this congruence is that $C_0$ can already be calculated! It's simply: $$C_0 \equiv A_0 B_0^{-1} \pmod{7}$$ where $B_0^{-1}$ denotes the modular inverse of $B_0$ modulo $7$. Thus, we already have the last digit, without even looking at almost all other digits of $A$ and $B$!

However, this only works if $B_0$ is not $0$. If $B_0 = 0$, then you can't invert $B_0$ any more to get $C_0$. But in this case, we can still do something. If $B_0 = 0$, then automatically we have $A_0 = 0$, which means that we can cancel the trailing zeroes. We'll be left with a new $A$ and $B$ with one less digit, but the last digit of this new $B$ is the old $B_1$. If this is again a zero, then we can repeat this process, until the last digit of $B$ is not a zero! So we can reduce every case to the case where $B_0 \not= 0$!

Now that we have $C_0$, how can we get the next digit, $C_1$? Since the last digit is $C_0$, we know now that $C$ is of the form $C'\cdot 7 + C_0$ for some $C'$, and that $C_1 = C_0'$, so we want to get the last digit of $C'$. Let's see what we can do: $$\begin{align*} A &= B\cdot C \\\ A &= B\cdot (C'\cdot 7 + C_0) \\\ A &= B\cdot C'\cdot 7 + B\cdot C_0 \\\ A - B\cdot C_0 &= B\cdot C'\cdot 7 \\\ (A - B\cdot C_0) / 7 &= B\cdot C' \end{align*}$$ Let's define $A' := (A - B\cdot C_0) / 7$ to be the value at the left hand side.

Notice that the latter is the same form as the original problem, so somehow we'll be able to extract the last digit of $C'$ if we have the value $A'$. But $A' = (A - B\cdot C_0) / 7$ can be computed in $O(\log_7 B)$ time! (Note that $B$ has $\Theta(\log_7 B)$ digits.) Because remember that $C_0$ is just a single digit, and when subtracting $B\cdot C_0$ from $A$ we only need to iterate through the digits of $B$, not $A$. Also, dividing by $7$ is simply moving the digits one place to the right, which at first glance seems to take $O(\log_7 A)$ time, but we can easily get around this. The following are a few ways:

  • We can represent $A$ as an array list with the digits stored in decreasing significance (so the least significant digit is last), because popping from the end of an array list can be done in $O(1)$ amortized time.

  • We can simply represent $A$ as a pointer to a position to the array and a number representing its length. Then to pop from the end of $A$, simply decrement the length!

So now that we have this number, we can now get $C_0'$ by recursively using the same method. Remember that $C_0'$ is really $C_1$. To get the next few digits, we simply repeat this until we get the $L$ digits we are looking for!

Optimizations

Since we're repeating this step $L$ times, and each step takes $O(\log_7 B) = O(\log B)$ time, the overall algorithm runs in $O(L \log B)$ time, which could pass the time limit if implemented with a couple of optimizations in mind. Here, we enumerate some.

First, after ensuring that $B_0 \not= 0$, we may use only the last $L$ digits of $A$ and ignore the rest. This is because by analyzing our algorithm above, notice that we won't ever have any use of all the higher-order digits of $A$. For instance, if we only want the last digit of $C$, then we only need the last digit of $A$. This reduces the amount of work to be done by about half, because the number of digits that need to be updated at each step decreases one by one.

Another way to look at it is the following:

If $B \not\equiv 0 \pmod{7}$, then there is a unique solution $x$ to $A \equiv B\cdot x \pmod{7^L}$, so if $A = B\cdot C$, then it must be the case that $C\bmod 7^L = x \bmod 7^L$. Thus, we are really only solving for the solution to the congruence $A \equiv B\cdot x \pmod{7^L}$, and we only really need the values $A$ and $B$ modulo $7^L$, i.e. the last $L$ digits of $A$ and $B$.

Second, we can further reduce the number of operations needed by operating in base $7^k$ rather than just base $7$. To maximize the effect, choose $k$ as large as possible such that $7^k$ is still below the signed 32-bit limit (to not cause too much headache about overflow). In the editorialist's solution, $k = 10$ is used. This reduces the number of "digits" of $A$ and $B$ by a factor of $k$, and also reduces the number of "digits" we want, $L$, by a factor of $k$, so the running time becomes $O((L \log B) / k^2)$ which is a good speedup! Now, the constant becomes higher because we now have to use larger int types, but still you'll find that this will give a noticeable improvement in running time.

Time Complexity:

$O(L \log B)$

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter
Tester
Editorialist

Viewing all 39796 articles
Browse latest View live


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