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

How do I win a CodeChef Goodie?

$
0
0

I want to know how can I get a CodeChef goodie? In which monthly contests, how many goodies are given? Does CodeChef also give certificates to the winners?


How to solve SPOJ GOODG?

MXDIST - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Bogdan Ciobanu
Tester:Xiuhan Wang
Editorialist:Taranpreet Singh

DIFFICULTY:

Hard

PREREQUISITES:

Convex Hull, Rotating Calipers, Range Minimum Query (RMQ) and bucket decomposition.

PROBLEM:

Given $N$ points and $Q$ queries $(f,t)$ specifying range $[f,t]$, find the maximum squared euclidian distance between any pair of points within the specified range.

QUICK EXPLANATION

  • Divide the points into buckets and build a convex hull for each bucket (preferably using Monotone Chain algorithm).
  • Build an RMQ sparse table considering each block as one unit, rmq[i][j] representing the convex hull formed by points from blocks in the range $[i,i+2^j-1]$. Hulls should be merged in $O(S)$ where $S$ represent the size of the hull.
  • Most distant point pair from a set of points can be easily found by using Rotating Calipers on the convex hull of the given set of points. To answer a query, make a convex hull consisting of points belonging to partially filled buckets and merge it into the appropriate pre-built convex hull from RMQ for intermediate blocks and calculate the answer.

EXPLANATION

Let us solve a trivial problem first. Given a set of points, find the maximum distance between any pair of points.

Lemma: The pair of points having the maximum distance lie on convex hull formed by points.

Proof: Let us assume we have a point pair AB being the most distant point pair, Point A strictly inside the convex hull and point B on or inside convex hull. Lt us extend this line toward A till it intersects the border of the convex hull, say at segment CD. Now, it can be seen, that at least one of $|BC| > |BA|$ or $|BD| > |BA|$ holds, which contradicts the fact that points $AB$ have the maximum distance. This contradicts our assumption. Hence, for the points to be most distant, both points shall lie on the convex hull.

Now, to find the maximal distance, we can use the rotating calipers technique, explained in brief below.

Let us have a pointer variable p and for every point indexed i, move it forward till the distance of (p+1)th point from the line formed by ith and (i+1)th point is more than distance of pth point from same segment, considering distance of pth and (p+1)th point from ith point. whenever moving from ith point to (i+1)th point, consider its distance of both these points from pth point. The maximum of all these is the distance of most distant point pair.

An important point to note is, that binary search is not going to work, as explained well here.

Merging Convex hulls

We merging convex hulls naively (assuming Monotone Chain algorithm is being used). In Monotone Chain algorithm, we find the points having leftmost and rightmost x-coordinate and build lower and upper convex hull separately. So, while merging, we can use merge-sort type technique to merge lower and upper hulls and removing the useless points in time proportional to the size of the convex hull.

Returning to original problem, we can build a RMQ sparse table, where RMQ[i][j] represent the convex hull formed by points in range $[i, i+2^j-1]$ which can be easily rewritten as the convex hull formed by merging RMQ$[i][j-1]$ and RMQ$[i+2^{j-1}][j-1]$. The details of RMQ can be found here.

Now, Let us evaluate the time complexity of this solution. During preprocessing, we have $log(N)$ levels having $N$ convex hulls. We can see, that merging convex Hull take time proportional to the size of convex hull, resulting in preprocessing time being $O(N*log(N)*S)$ after which, each query may take $O(S)$ time as both merging convex hull and calculating most distant point pair take $O(S)$ time.

Now, the question is, what is the size of the convex hull? We have randomly generated points in the second sub-task while worst cases in the third sub-task. It can be seen from research that the expected number of points in convex hull of $N$ randomly generated points is roughly of the order of $N^{1/3}$ while if we generate points carefully in $MX*MX$ grid, we can have up to around $MX^{2/3}$ points in convex hull, $MX = 2*10^5$ in our case. This explains the difference in time complexity of the same solution for second and third sub-task. See references here and here.

Now, we see, though it may be sufficient with optimizations to pass this solution for the second subtask, it shall be hard to pass the final subtask. So, Let us optimize the preprocessing part to fit the time limit by bucket decomposition.

Let's first divide all $N$ points into blocks of size $SZ$ and now, build RMQ considering each block as one position in RMQ. This way, to answer queries, we can use RMQ to find convex hull formed by points in intermediate blocks and naively build a temporary convex hull by points which lie in partially filled blocks (can be at most 2 for each query). We can merge these two blocks and calculate the answer for this block.

Now, Let us calculate the time complexity of this solution. If $C = \lceil N/SZ \rceil$, we can build RMQ on blocks in $O(S*C*log(C))$ time and answer each query in $O(SZ+S)$ time, resulting in time complexity $O(S*(N/SZ)*log(N) + Q*(S+SZ))$. It works fast enough for $SZ = sqrt(S*N*log(N)/Q)$.

Editorialist solution

The editorialist who like different solutions, choose to use graham scan as means of building and merging convex hulls as opposed to Monotone Chain algorithm in case of setter and tester solution. This slows down editorialist's solution by $log(S)$ due to the fact that for Graham scan, sorting by the polar angle is required while in Monotone Chain algorithm, merging convex hull can be done in merge sort type manner in $O(S)$ for both lower and upper hulls. This is the reason Monotone Chain algorithm is preferred to Graham scan in this problem.

An interesting problem to try is GEOCHEAT.

Time Complexity

Overall time complexity is $O(S*(N/SZ)*log(N/SZ) + Q*(S+SZ))$ where $SZ$ is the block size chosen.

Space Complexity is $O(N+S*(N/SZ)*log(N/SZ))$.

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. :)

Brief Editorials ICO Preparatory Mega Contest ICOP1904

$
0
0

As @mgch quoted here, who am I to contradict him. So, I am presenting you the brief editorials for ICO Preparatory Mega-Contest. Hoping you all guys had fun in this contest. Here we go!

SHIVIGOD

For every x in range A to B, run sliding window of size x maintaining the sum of elements in ranges of length x, and take the one having the maximum average. Read about Sliding window here. The max(max sum in the range of length x/x) is the answer. Time complexity $O(N^2)$.

SSJG

Build prefix arrays in 2d to compute the sum of subgrid in O(1) time as explained here and for each intersection point, calculate the values of all 4 subgrids if the current intersection is chosen and take the min. The intersection has the maximum value of min is the best intersection. Time complexity $O(N^2)$.

JVPHOBIA

We run a DFS from each node maintaining an included array. The thing is, that once we consider one friend, there's no benefit to consider him again. So, Running DFS only on non-included nodes at each step leads to a solution in $O(N)$ time.

GRP

This problem is dynamic programming. We precompute cost(i, j, k) being min cost to convert array range [i, j] to bit k, k being 0 or 1.

Now, Let us use dynamic programming with two states, index of array covered and bit at ith node. DP[i][j] = min(DP[i-j][k^1]+cost[i-j+1][k]) for all $x \leq j \leq y$. Time complexity $O(N^2)$.

TREEDGE

It is tree DP, for each node x, calculate DP(x) = max length path from x to any node in the subtree of x, which has a maximum length. The minimum value of DP(x) is 0 since we can always have a path from x to x itself.

For query u, v, we join two nodes in the subtree of u and v, to get max path length DP(u)+dp(v)+w.

Now, only 2 paths exist between u and v. One with length DP(u)+dp(v)+w and the other from u to LCA(u,v) to v, the length of which can be precomputed computed by DP or binary lifting.

Time complexity is $O(N*logN+Q*logN)$. Dp can be precomputed in $O(N)$ time, overall time complexity dominated by LCA finding.

STRGRA

We use DP[i][j] meaning min cost to reach node i after covering first j characters of the string. Clearly, at each character, we can run multisource Dijkstra to compute min cost to other vertices. Now, Core thing is, for next step, consider only those vertices as the source which have s[j] == a[i]. This way, answer is min(dp[i][|s|]) for i such that a[i] == s[|s|-1]. Impossible cases include disconnected graphs and character not present at all.

Time complexity is $O(|S|*(N+M)*log(N))$.

Hope you guys had a nice contest.

Why aren't practice links activated immediately after the contest is over?

$
0
0

I badly want to test my solution to a problem in ALOHOMORA. I cannot imagine any reason why practice links cannot be activated immediately after the contest is over.

Snackdown T-shirts?

$
0
0

When will they be sent? Will they be sent according to address on codechef profile? Do I only need to fill the address and wait? (BTW what language should i use in the address) Thanks!

YVNUM Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author and Editorialist:Hussain Kara Fallah
Tester:Michael Nematollahi

PREREQUISITES:

NONE

PROBLEM:

Given a decimal integer $N$ (with no zeroes at all even as intermediate digits). Consider all left cyclic shifts of $N$. The left cyclic shift is the operation of removing the leftmost digit from the number and appending it to the end.

Suppose $N = 123$ then all left cyclic shifts are {123,231,312}. So you start with $N$ and repeat the mentioned operation $N-1$ times.

Yalalovichik number of $N$ is equal to the concatenation of all these cyclic shifts.

For the previous example:

$Y = 123231312$.

Given $N$, you need to compute the value of $Y$ modulo $10^9+7$

Length of $N$ may reach $10^5$

EXPLANATION:

Let's assume that length of $N$ is equal to $L$. We know that:

$N = a_0*10^{L-1} + a_1*10^{L-2} + a_2*10^{L-3} + ... + a_{L-1}$

Assuming that digits are indexed from $0$ to $L-1$ and from left to right. $a_0$ represents the leftmost digit. So let's assume we need to do one shift operation, how to erase the leftmost digit?

$N' = N - a_0*10^{L-1}$

$N'$ is equal to the value of $N$ after removing the leftmost digit.

Let's assume that the number resulting from the shift is $M$ so:

$M = N' * 10 + a_0$

so now the number resulting from the shift is $M$ we need to append it to our final answer. At the beginning the answer $ans = N$. To append it let's shift $ans$ to the left by $L$ digits and simply add $M$.

$ans = ans * 10^L + M$

This is for the first shifting operation, to solve the problem repeat this operation $N-1$ times, but don't forget to continue working on the shifted number.

We only need to calculate $10^L$ and $10^{L-1}$, this can be done in linear time or faster if you prefer.

To maintain the answer modulo $10^9+7$ we calculate the powers mentioned above modulo $10^9+7$ and we always take our results modulo $10^9+7$ after each subtraction or multiplication or addition.

Refer to the implementations for more details.

Total Complexity $O(L)$

AUTHOR'S AND TESTER'S SOLUTIONS:

AUTHOR's solution

TESTER's solution

Shivigawdz ICOP1904 Debugging

$
0
0

I cannot understand what is wrong with my code here. I have applied sliding window algorithm over a range of possible length say k belonging to [A,B]. I just don't understand where I went wrong. Please help me out.


How to take input from user in multiset in C++. Following in not working. Please help me.

$
0
0

while ((N--)!=0 && cin>>input) multiset1.insert(input);

CARVANS - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

CAKEWALK

PREREQUISITES

Simple Math

PROBLEM

There are N cars on a narrow road that are moving in the same direction. Each car has maximum speed. No car can overtake other cars on this road. Each car will move at the maximum possible speed while avoiding any collisions. Count the number of cars which are moving at their maximum speeds.

QUICK EXPLANATION

Intuitively, a car is moving at its maximum speed if and only if all cars in front of it are moving at greater speeds (otherwise it will overtake the slower car). Therefore, the answer is the number of such cars.

EXPLANATION

Suppose that the cars are numbered 1 through N from front to back, and the maximum speed of the i-th car is maxSpeed[i]. From the intuitive observation above, we can directly come up with this naive solution:

answer = 0
for i = 1; i <= N; i++:
    allGreater = true
    for j = 1; j <= i-1; j++:
        if maxSpeed[j] < maxSpeed[i]:
            allGreater = false
    if allGreater:
        answer = answer + 1

Unfortunately, this solution runs in O(N^2) time, which will surely time out. We will need other observations.

Consider each car. From the problem statement, each car will:

  • Avoid any collisions. Since the road is narrow, therefore, it will not move at greater speed than the car directly in front of it (if any).
  • Move at the maximum possible speed. Therefore, it will move at speed of exactly min(the maximum speed of the car, the speed of the car directly in front of it).

From those observations, we can calculate the speed of each car in O(1) time. When calculating the speed of the i-th car, we have to know the speed of the (i-1)st car. Therefore, we must calculate the speeds in the right order (i.e., from the first car to the last car on the road). After that, we compare the speed of each car with its maximum speed.

A direct implementation of the above solution is as follows. This solution runs in O(N) time, which will pass the time limit.

answer = 0

speed[1] = maxSpeed[1]
for i = 2; i <= N; i++:
    speed[i] = min(maxSpeed[i], speed[i-1])

for i = 1; i <= N; i++:
    if speed[i] == maxSpeed[i]:
        answer = answer + 1

Exercise

Try to solve this problem without creating the additional speed[]/maxSpeed[] array. Hint: we can always store only the speed of the last car we consider instead of storing all speeds in speed[] array.

SETTER'S SOLUTION

Can be found here

TESTER'S SOLUTION

Can be found here.

What is the meaning of pairwise distinct integers?

$
0
0

I am a newbie on Codechef. Any help will be appreciated :) If it is given in the problem statement that : "All elements of the given array are pairwise distinct, does it mean that all the elements of the array are distinct ?" Thanks in advance! :)

Help in a question

$
0
0

You are given N segments on the x-axis. You should partition them in at most k sets. For each set, we define its cost as the length of the intersection of the segments in the set. Find the partition that maximizes the sum of the cost of all the sets.

Input:
The first line contains the two integers N and k.
Each of the following N lines contains two integers x1 and x2 representing the end points of a segment.

Constraint:
N <= 6000
k <= N
x1 < x2 < 10^6

Can someone please help me with this problem.

HORSES - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

DIFFICULTY

CAKEWALK

PREREQUISITES

Sorting, Quick Sort

PROBLEM

You are given a list of integers. Find the pair of integers whose value is closest among all the pair of integers in this list.

QUICK EXPLANATION

You can sort the integers and then consider all (N-1) consecutive pairs of integers. One of these pairs is surely the closest. Their difference is the answer.

EXPLANATION

First, let us consider the complexity of a naive brute force solution.

If we consider each possible pair of integers, we will end up with an O(N*N) solution - given there are N integers.

For a file with T test cases, the over all complexity is O(N*N*T). This will mean about 250 million calculations. This will be too slow to pass within 3 seconds on the CodeChef servers.

As with any brute force solutions, this solution is doing a lot of extra work. It is considering the difference between several pairs of integers that can be ignored.

Consider the case where the list of integers - we will call it A - is sorted.

Lemma:

The closest pair of integers is one of the N-1 pairs, which appear consecutively in A

Alternately, if A[i] and A[j] are the closest pair of integers, then i is equal to j-1.

Proof:

We will use Proof by Contradiction.

Let us assume that the pair of closest integers is A[i] and A[j] and i < (j-1)

  1. Consider A[k]k > i and k <= (j-1)
  2. Since A is sorted, A[k]>=A[i] and A[k]<=A[j]
  3. From (2) we get A[k] - A[i]>=0
  4. Adding A[j] - A[k] on both the sides in (3) we get
    A[j] - A[i]>=A[j] - A[k]

Hence, A[k] and A[j] are either a better or an equally good choice for pair of closest integers.

This means, at least one of the assumptions is false.

  • Either A[i] and A[j] are not the closest integers
  • Or, i is equal to j-1

Approach:

Now, we just need to sort the numbers efficiently and consider the consecutive pairs in one parse. Sorting can be done in place using the Quick Sort algorithm, which sorts in O(N log N) time. Quick Sort is available in the standard library in almost all languages.

The rest can be resolved in a single parse. The code will look like

Sort A
minval = infinity
for i = 1 to N-1, inclusive
    if minval > A[i] - A[i-1] then minval = A[i] - A[i-1]
print minval

SETTERS SOLUTION

Can be found here

TESTERS SOLUTION

Can be found here

Philosophers Stone - Editorial

$
0
0

Problem Link : Link

Author : Shivansh Agarwal
Tester : Ritesh Gupta
Editorialist : Ritesh Gupta

Pre-Requisite : None

Problem : You are given an unsorted array of integers. You have to find that all the elements are distinct or not.

Explanation : There are many approaches to solve this question. You can use std:set to store the elements of the array. If the size of the set is not equal to the size of the given array then there exists some element which occurs more than once.

Time Complexity : O(nlogn)
Setter Solution : Link
Tester Solution : Link

ALORA3 - NZEC with Python

$
0
0

I am facing a problem with the Prisoner of Azkaban problem. This is my solution. It has been written in Python 3.x . Its getting NZEC. Can anyone point out where am I going wrong? The weird part is that it has no solutions in Python. SO can't really figure it out. Any Test cases or any hint would be highly appreciated. Thanks in advance


How to prepare for Google HashCode?

$
0
0

What are the subject areas/topics that Google HashCode focuses on? Can you please specify the algorithms that one should focus on and some resources where one could practice for this contest? Which language is most suitable/preferred for the contest?

Help understanding a question in the current cook-off

$
0
0

Hello everyone. This is a question of the ongoing January Cook-Off 2019. I do not need any hints for the answer, I just need some clarification for the question. I have asked the relevant doubts in the comments of the question, here's the link for the comments:

https://drive.google.com/open?id=1qVgsF8HF7llgqPYwxg4UvzZmucIU9--p

Here's the link for the question:

https://www.codechef.com/COOK102B/problems/ADAKNG

Can someone please explain with an example as to what I exactly need to do? Help appreciated, thanks a lot!

Doubt related to a Dynamic Programming problem!

$
0
0

I sincerely hope, that this question does not belong to any ongoing contest : D @aryanc403

If it does, please don't answer this question :)

We are given integers,namely, a,b,c and d. Also, 0<=a,b,c,d<=1000

We have to satisfy this equation : a+b^2+c^3+d^4<=S,

where , 0<=s<=10^18

We will be given an integer, 'S' as the input.

We have to find the no. of integral solutions which satisfy the above equation!:)

I know the brute-force way, can anybody propose a nice dp-way to solve it? Thanks.

Link to the sequence :----> https://oeis.org/search?q=1%2c4%2c7%2c8%2c9%2c11%2c12%2c12&fmt=data

Bug in UI of CodeChef !!

$
0
0

I accidentally set my profile picture to a image which is long in height. I clicked on Additional Information in Profile Edit section and now I cannot change my profile picture,Personnel and Professional settings as those two links covered by the long picture. In order to reproduce the bug set this image https://s3.amazonaws.com/codechef_shared/sites/default/files/uploads/pictures/b47b8f2b5a7d349ba626844331d4bb4d.jpg as your profile picture and click on Additional section in Profile Edit section.

Please fix it soon.

Brute force with tc O(n^3) works?!That too in a contest?

$
0
0

Is there really no other efficient approach other than brute force for this problem? Because brute force seems to be working just fine for that kind of input.

Viewing all 39796 articles
Browse latest View live


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