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

Can anyone teach me DP on trees with the help of solving this question?

$
0
0

I came across this problem (DP on trees): http://acm.timus.ru/problem.aspx?space=1&num=1018

I solved some beginner level problems on DP but I am not able to get the logic of this particular topic. I tried reading about this topic on the IARCS website (link) but I couldn't understand it completely. Can anyone explain me DP on trees along with solving the question given above? (I mean, like a proper tutorial. Since there are very few good resources on DP on trees, it would help all of them searching for this topic)


Snackdown goodie dispatch

$
0
0

Hi,

is there any information regarding Snackdown 2015 T-shirt dispatch? I haven't heard from organizers in a long time, so I was just wondering when could we expect the deliveries to happen?

Regards, RandomUsername

Contribution - AUGUST 2015

$
0
0

Dear @admin

The goodies for AUGUST contribution is not yet dispatched, it has been 2 months since I have mailed you guys. And you people dont reply to our emails.Email See this issue.

Thanks.

CodeChef does not restored ratings

$
0
0

I was wrongly penalized in the October challenge and i received an email saying all my ratings would be dropped. It was because my solution was found similar to another solution (This question had over 4500 submissions so it follows that someone could have the same trivial logic).

http://www.codechef.com/viewsolution/8467842 (My solution)
http://www.codechef.com/viewsolution/8310972 (Other solution)

I have written 6 emails to Rudreshwar@codechef.com, explaining in 1 of them how my code was different and how I had submitted on 9th OCT and the other was submitted on 2nd. A lot of other difference as well. I didn't get a reply on any of those.

I called up codechef and got a posivtive reply and they said they would restore my ratings when the November challenge ratings were calculated. I solved 5 problems in the November Challenge and was hoping that my ratings for October would be recalculated as well.

I also messaged codechef on FaceBook and got a reply that they would surely restore them

Finally today, the ratings were alculated but my ratings were not restored. They keep someone hanging for a month and finally don't live up to their words. I don't think this is done.

I have deep respect for the CodeChef and it's team and know that they are selflessly trying to uplift the programming culture in India but if you are wrongly accusing someone of doing someone and not rectifying it and then sending an email that ' If the MOSS has thrown a false warning, please get in touch with us' is not right. If you are not going to restore them, atleast don't send us emails that say that you will restore the ratings.

I would like to ask anyone if they have face the same problem and if their rating has been restored or not

ZCO Matched Brackets 2

Given an array of integers, divide the array into k subarrays such that the difference between the maximum sum and minimum sum subarrays is minimised

$
0
0

For example, let us consider dividing the following array into 5 subarrays:

[0,1,2,1,3,1,5,6]

The optimal way to divide this is [0,1,2],[1,3],[1],[5],[6] since the maximum sum subarray has sum 6 and minimum sum subarray has sum 1, and 5 is the best possible result that you can get.

The algorithm that I can think of iterates through all possible ways of partitioning the array into k parts and choosing the best of them all. This is clearly exponential. Is there a polynomial time algorithm?

A Dance with Mobius Function

$
0
0

In this post I am going to share my little knowledge on how to solve some problems regarding Mobius Inversion Formula. I chose this topic because it has a lot of varieties of problems (mostly categorized as medium or hard), but has very few good blogs explaining the theory behind. I have tried to present a generalized approach in solving the problems in this topic.

Prerequisite: High School mathematics is enough to understand this blog.

Beware! This post contains a lot of things which are not proved but are left as an exercise. So wherever it is mentioned as to prove by yourself, I recommend you to stop there and try to prove those and then only move forward so that there won't be any confusion.

I am going to explain how to solve the problems GCDEX and COPRIME3 below. But, before going into the actual solutions, first, we need to know a little bit about what the mobius inversion formula is, what a mobius function is, how to manipulate the summations, etc. This topic has a lot of fascinating theory behind it. If you are well equipped with the theory part, then solving any algorithmic problem of this topic will be a cake-walk with less than 5 to 6 steps of reduction, which might look obvious.

I strongly recommend reading this article before proceeding as it will make things extremely easy to understand. It has awesome theory on multiplicative functions and many theorems with proofs. There are also many problems with hints and solutions for a few. Some definitions and literature from the article is explained below for better understanding.

Throughout this topic we are only going to deal with integers and multiplicative functions.

An arithmetic function f(n) : N → C is multiplicative if for any relatively prime n, m ∈ N: $f(mn) = f(m)f(n)$.

From now on we shall write the prime decomposition of n ∈ N as $n = p_{1}^{α_{1}} * p_{2}^{α_{2}} * p_{3}^{α_{3}} * ... * p_{r}^{α_{r}}$

Let us define some functions :

  1. e(n), the Dirichlet identity function
    $e(n) = 1$ for n = 1,
    $e(n) = 0$ for n > 1;

  2. I(n) = 1 for all n ∈ N;

  3. id(n) = n for all n ∈ N;

  4. µ(n), the Mobius function;
    $µ(n) = 1$ if $n = 1$,
    $µ(n) = 0$ if n is not square-free, i.e $α_{i} > 1$ for some prime factor
    $µ(n) = (−1)^r$ if $n = p_{1} . p_{2} · · · p_{r}, p_j$− distinct primes.
    Mobius function is an interesting function with amazing properties. We will see why it is, later.

  5. For any function $f(n)$, lets define the sum function, $S_{f} (n)$ as the sum of f(d) for all factors d of n, i.e, $S_{f} (n) = \sum_{d|n} f(d) , (a | b)$ means that a is a factor of b, or simply a divides b.

  6. Euler totient function ϕ(n) is the number of the integers d between 1 and n which are relatively prime to n (set ϕ(1) = 1.)

Dirichlet Convolution:

For any two functions f(x) and g(x), the dirichlet convolution is defined as

$f O g(n) = \sum_{d1*d2=n} f(d1) * g(d2)$ or $f O g(n) = \sum_{d | n} f(d) * g(n / d)$

The Dirichlet product, O, is commutative, and associative:

$f O g(n) = g O f(n)$

$(f O g) O h(n) = f O (g O h)(n)$

You can prove these by yourself easily.

Now some interesting observations:

$S_{f} (n) = \sum_{d|n} f(d) = \sum_{d|n} f(d) * I(n / d)$

Or simply,

$S_{f}(n) = f O I(n)$, i.e, Dirichlet convolution of the functions f(x) and I(x) (the function I(n) is defined above)

$S_{ϕ}(n) = \sum_{d|n} ϕ(d) = id(n)$ Proof left as an exercise.

$S_{µ}(n) = \sum_{d|n} µ(d) = e(n)$ Proof left as an exercise.

The above formula can be re-written as $S_{µ}(n) = I O µ(n) = µ O I(n) = e(n)$.

$f O e(n) = \sum_{d|n} f(n / d) * e(d) = f(n)$, because e(d) is equal to 1 only when d = 1.

Now, $S_{f} O µ(n) = (f O I) O µ(n) = f O (I O µ)(n) = f O e(n) = f(n)$.

Or Simply

$f(n) = \sum_{d|n} S_{f}(d) * µ(n / d)$. This is called the famous Möbius inversion formula.

Now lets see how this concept is useful in solving problems.

Problem :

Find $G = \sum_{i=1}^{n} \sum_{j=i+1}^{n} gcd(i, j)$ -- (Eq.1), gcd(i, j) is the Greatest common divisor of i and j.

Solution:

The brute force approach: Iterate through all i and j, and find the sum of their gcds. This will take $O(N^2 * k)$ time, where k is the maximum number of steps needed to calculate gcd of two numbers.

Using Mobius Inversion Formula:

It is easy to see that the gcd of any pair (i, j) : (1 <= i < j <= n) will be between 1 to n.

So the summation $G = \sum_{i=1}^{n} \sum_{j=i+1}^{n} gcd(i, j)$ can be re-written as

$G = \sum_{g = 1}^{n} g * cnt[g]$--(Eq.2)

Here cnt[g] = Number of pairs (i, j) such that 1 <= i < j <= n and gcd(i, j) = g. It is not trivial to find number of pairs (i, j) such that whose gcd is equal to g. Here gcd(i, j) = g implies, gcd(i/g, j/g) = 1. The relation between i and j is that i/g and j/g should be co-prime.

Lets try something else here.

The equation 2 can be re-written as

$G = \sum_{g = 1}^{n} h(g) * cnt[g]$

Where $h(g) = g$ in this question.

Now lets try to write h(n) as sum function of some function f(n), i.e, $S_{f}(n) = h(n) = \sum_{d|n}f(d)$

f(n) can be found by using mobius inversion formula, $f(n)= \sum_{d|n} h(d)*µ(n / d)$.

The Mobius function µ(n) can be found using a similar sieve which we use to find the prime numbers, see this Sieve Methods : Prime, Divisor, Euler Phi etc. - Codeforces for some help.

If we know h(n) and µ(n), f(n) can be found by using a sieve like this:

[code] for (int i = 1; i <= N; i++) { for (int j = i; j <= N; j += i) { f[j] += h[i] * µ[j/i]; } } [/code]

The above code runs in O(N * logN) time. The reason is, for each i, the inner for loop runs N/i times (i.e, number of multiples of i), and as $\sum_{i=1}^{n}N/i = O(N * logN)$.

In this problem, as $h(g) = g, f(n) = \sum_{d|n} d * µ(n / d)$. simplifying this we get $f(n) = ϕ(n)$. This is left as an exercise.

Now G in equation 2 will become

$G = \sum_{g = 1}^{n} (\sum_{d|g} f(d)) * cnt[g]$--(Eq.3)

which can be rewritten as

$G = \sum_{d = 1}^{n} f(d) * (\sum_{g : d | g} cnt[g])$--(Eq.4)

Let us define cnt2[d] as $cnt2[d] = \sum_{g : d | g} cnt[g]$

What exactly does cnt2[d] represent?

It is the count of number of pairs (i, j) such that gcd(i, j) is a multiple of d. Here the relationship between i and j is simple. There is no such relation between i and j that (i/d and j/d) should be coprime. It is only required that gcd(i, j) is a multiple of d, which means both i and j should be multiples of d. This is necessary and sufficient condition. Number of multiples of d between 1 and n is equal to n/d. So number of pairs (i, j) such that (i < j) and both i and j are multiples of d, will be equal to (n/d) * (n/d - 1) / 2 (Why?)

So our equation 4 becomes

$G = \sum_{d = 1}^{n} f(d) * (n/d) * (n/d - 1) / 2$.

One important observation we need to make here is that the value of (n/d) will take only O(sqrt(n)) distinct values. It is not very hard to prove this.

So we can iterate through all distinct values of (n/d) and add the term $(n/d) * (n/d - 1) / 2 * \sum_{k: n/k = n/d} f(k)$ to the final answer.

In the term $\sum_{k: n/k = n/d} f(k)$ all the k's will be consecutive, so if we maintain prefix sums of f(i), we can find this term in O(1).

Complexity of this solution is $O(N * log(n) + sqrt(n) * T)$ T = Number of Test Cases.

The whole idea can be generalized like this:

  1. Let the problem be to find $ G = \sum_{i = 1}^{n} \sum_{j=i+1}^{n} h(gcd(i, j))$, here h(n) should be a multiplicative function. For example if the problem was to find $ G = \sum_{i = 1}^{n} \sum_{j=i+1}^{n} gcd(i, j)^3$ , then the function h() will be $h(n) = n^3$.

  2. Re-write the equation like this: $ G = \sum_{g = 1}^{n} h(g) * cnt[g]$ Where cnt[g] = number of pairs (i, j) such that gcd(i, j) = g, (1 <= i < j <= n).

  3. Find the function f(n), such that $h(n) = \sum_{d|n}f(d)$. This can be done using mobius inversion formula and sieve.

  4. Rewrite the equation in second step like this, $G = \sum_{d = 1}^{n} f(d) * cnt2[d]$.

  5. Iterate through the O(sqrt(n)) distinct values of cnt2[d] and find the answer in O(sqrt(n)) time.

Using the knowledge of above method lets solve the problem COPRIME3

  1. Here the question is to find the number of triplets (i, j, k ) such that 1 <= i < j < k <= n, gcd(a[i], a[j], a[k]) = 1.
    Or simply,
    Find $G = \sum_{i=1}^{n} \sum_{j=i+1}^{n} \sum_{k=j+1}^{n} e(gcd(a[i], a[j], a[k]))$.
    Here the function e(n) is the dirichlet identity function, i.e, e(n) = 1 if n = 1, e(n) = 0, if n > 1, which means that 1 is added to the final answer if the gcd(a[i],a[j],a[k]) is equal to 1.

  2. Now rewrite the equation like this $ G = \sum_{g = 1}^{maxg} h(g) * cnt[g]$.
    Here cnt[g] = Number of triplets (i, j, k) such that gcd(a[i], a[j], a[k]) = g, maxg will be equal to $10^6$ in this question.

  3. Find the function f(n), such that $h(n) = \sum_{d|n}f(d)$. This can be done using mobius inversion formula and sieve. In this problem f(n) will be simply equal to µ(n).
    Then the problem becomes to find $ G = \sum_{g = 1}^{maxg} (\sum_{d:d|g} f(d)) * cnt[g]$.

  4. We can rewrite the equation in second step like this, $G = \sum_{d = 1}^{maxg} f(d) * cnt2[d]$.
    Here cnt2[d] is number of triplets (i, j, k) such that gcd(a[i], a[j], a[k]) is a multiple of d. If dp[x] is the number of i such that a[i] is a multiple of x, then cnt2[d] will be simply Choose(dp[x], 3). Choose(n, r) = number of ways to choose a combination of r items among n distinct items. The values of dp[x] can be found using a sieve.

  5. Iterate through all d and find the $G = \sum_{d = 1}^{maxg} f(d) * cnt2[d]$.

Complexity: O(N * logN) for the sieve.

Finally, Here are some exercises for you to try

http://www.codechef.com/JULY10/problems/LCM/
http://www.codechef.com/COOK29/problems/EXGCD
https://www.hackerrank.com/challenges/hyperrectangle-gcd
http://www.spoj.com/problems/LCMSUM/
http://www.spoj.com/problems/GCDEX2/

Coding @ Codechef

$
0
0

I am into competitive programming recently. Off many of the coding websites, Codechef has one of the best user-interface and great classification of different level problems. It Would be even better if codechef provides test-cases for which the code fails in practice problems section. This Would: Help in correcting or debugging code ourselves. It also prevents the users to look up for others' code. Ofcourse that helps but it eradicates the need to think on our own. Providing the test cases in practice problems also give the user an idea of what type of test cases are provided in a contest and it significantly improves coding skills.


MNMX - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

Author:Sunny Aggarwal
Tester:Alex Gu and Pushkar Mishra
Editorialist:Prateek Gupta
Russian Translator:Vitalij Kozhukhivskij
Vietnamese Translator:Khanh Xuan Nguyen
Mandarian Translator:Gedi Zheng
Contest Admin:Praveen Dhinwa and Pushkar Mishra

DIFFICULTY:

Simple

PREREQUISITES:

None

PROBLEM:

Given an array of size $N$, you have to reduce the array into a single element by repeatedly applying a single operation.
The operation involves picking up two adjacent elements in the array and remove larger of them by paying a cost equal to smaller of them. Minimize the total cost.

EXPLANATION

Solution for Subtask 1:
This subtask can indeed be solved by Bit Masking DP. Check this link to know more about Bit Masking. In this case, we maintain a state $F(mask)$ where in, set bits of mask represent which all indexes have been removed uptill now. We want to arrive at a state where only the last element i.e only 1 unset bit remains in the final array. The last index remaining will always be the position of minimum element in the array regardless of the order of applied operations. Lets look at the pseudo code to understand how this recurrence works.

F(mask) {
   if ( __builtin_popcount(mask) == n-1 ) return 0
   long long ans = 0
   for ( int i = 0; i < n; i++ ) {
       if ( !(mask & (1<<i)) ) {
            int j = i+1
            while ( j < n && (mask&(1<<j)) ) j++
            if ( j != n ) {
                int remove_idx = (A[i] > A[j]) ? i : j
                ans = min(ans, min(A[i],A[j]) + f(mask | (1<<remove_idx)) )
            }
       }
   }
   return ans
}

Basically, at any particular state, we are checking what all indices are there which have not been removed yet. So for this, we try to apply all kinds of $X-1$ operations for any $X$ unset bits. We take a bit which is not set, lets call it $i$, we find the just next unset bit $j$, which would mean these two are consecutive elements at that particular state and hence, the greater of them can be removed. We do this for all such $(i,j)$ pairs to take the minimum of all answers. Minimum value returned by calling function $F(0)$ will hence be the minimum cost spent to convert the array into a single element. Overall Complexity for this naive approach is $\mathcal{O}(2^N*N^2)$


Solution for subtask 2 & 3:
In order to minimize the total cost, you should surely choose the pair of consecutive integers consisting of the smallest element in the given array. The minimum element will anyway be the last remaining element after all operations have been applied. So, why not choose a pair of consecutive numbers involving this minimum element till the whole array reduces to this minimum element. Since, we need to perform this operation $N - 1$ times, total cost incurred will hence be equal to $(N - 1)*(MINVAL)$. As answer can be little large, use a data type which can handle larger numbers.

COMPLEXITY

As minimum value in the array can just be found in a single traversal, overall complexity of the solution is $\mathcal{O}(N)$.

SOLUTIONS

Tester

NUMFACT - Editorial

$
0
0

Author: Vamsi Kavala
Tester: Roman Rubanenko
Editorialist: Bruno Oliveira

PROBLEM LINKS

Practice
Contest

DIFFICULTY

Cakewalk

PRE-REQUISITES

Simple Math, Integer Factorization

Problem:

You are given a very large number represented as a product of N numbers. Given this number representation, you need to find the number of distinct factors of the original number which is formed by the product of given N numbers.

Quick Explanation:

We can factorize each one of the N given numbers into its prime factors. Then we find the number of occurrences of each prime factor, say they are a1, a2,...aK, if we have K distinct prime factors. Our answer is simply: (a1+1)(a2+1)(...)*(aK+1).

Detailed Explanation:

This problem relies on some knowledge of divisor function. Divisor functions returns the number of positive and distinct divisors of a number. Let's call it d(x).

  • Some properties of the divisor function:

    We now look into some important properties of the divisor function:

    For a prime number p, we have d(p) = 2, as there are only two numbers which divide a prime number:1 and itself.

    Now, it's a known fact that this function is multiplicative but not completely multiplicative. This means that if two numbers, say, a and b are there such that gcd(a, b) = 1, then the following holds:d(a*b) = d(a)*d(b).

This allows us to deduce the important relationship, that is the key of solving this problem:

For a prime number, p, we have: d(p^n) = n+1.

Now, it's easy to understand that all we need to do is to factorize all the N given numbers into its prime factors, and, for each prime factor we also need to count how many times it appears (that is, we need to know the exponent of each prime factor).

Once we have this count with us (which can be done using integer factorization and for example, the set and map data structures, one to guarantee uniqueness of the factors and the other to save the number of occurences for each unique prime factor), all we need to do is to multiply all these numbers plus one together and we will obtain our answer.

As an example, consider the number:

504 = 2^3 * 3^2 * 7^1

The number of distinct divisors of 504 is then (3+1) * (2+1) * (1+1) = 24.

Applying this process to all numbers yields the answer to the problem :)

SETTER'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Tester's solution will be uploaded soon.

Useful Links

What is a multiplicative function?
More information on the divisor function

SANSKAR give some test case where the code fails?

How to execute the program ?

$
0
0

Every i write code on codechef it shows correct output for sample cases but when i submit i display wrong answer,what can i do to solve these problems

Can anyone please train me to become a better programmer?

$
0
0

I am a CSE student at Bangladesh University of Engineering and Technology. I am quite interested in programming but my journey would be more enjoyable, if I can find an experienced programmer to help me in this regard. It would be greatly helpful

DRAGNXOR - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

EASY

EXPLANATION

We need to make A^B maximum by shuffling the 1 bits within A and B. As 1 ^ 0 = 0 ^ 1 = 1, we need to make maximum number of (1,0) or (0,1) pairs, where a pair means the corresponding bits from A and B at a particular bit position. Also, to make the result maximum, we want all the ones towards the most significant side (left). Lets pair each 1 bit of A with a 0 bit of B. There can be at max x = minimum _ of( number of 1s in A, number of 0s in B). Similarly, pair each 1 bit of B with a 0 bit of A. There can be at max y = minimum _ of( number of 1s in B, number of 0s in A). Rest of the pairs are either (1,1) or (0,). So, the number of ones in the result is at max P = x + y. The answer is (1111...) : P times followed by (...000) : N-P times, which is nothing but the integer ( ((1<<P)-1) << (N-P) ).

SETTER'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Can be found here.

FFT problem

$
0
0

Hello
I am trying to solve this question: http://sharecode.io/contests/problem/61839756/F
I used the fft implementation of stanford's team notebook: http://stanford.edu/~liszt90/acm/notebook.html#file16

Here is my code: link

I am getting wrong answer on it. I have tested lots of different tests on it but I couldn't find the error. Now I am not sure what to do. Could it be because of double's error or is it something else? If that's the case could anyone provide an implementation of real FFT?

a brief description of the problem: Given the coefficients of two polynomials calculate the coefficients of their multiplication.


Nov Short Contest Ratings

$
0
0

Hi, i think there is a bug in short contest ratings.... The ratings in cookoff are updated ,but it still shows as oct in the graph.... is it because that the previous short contest being unrated?

SUBLCM - editorial

$
0
0

PROBLEM LINK:

Practice
Contest
Author:Lalit Kundu
Tester:Tasnim Imran Sunny
Editorialist:Devendra Agarwal

DIFFICULTY:

Medium

PREREQUISITES:

LCM and Dynamic Programming

PROBLEM:

Given an array A1,A2...AN you have to print the size of the largest contiguous subarray such that LCM of all integers in that subarray is equal to the product of all integers in that subarray.

Solution:

Problem Idea: Calculating efficiently longest subarray which ends at i for each i. LCM of all integers in that subarray is equal to the product of all integers in that subarray.

Let Dp[i] denotes the length of the longest subarray ending at i and satisfying the property that the product of all integers of the subarray is LCM of the subarray.

If we know Dp[i-1] , can we calculate Dp[i] ?

Yes , Dp[i] = min ( Dp[i-1]+1 , i - Cal(i) ) (Array indexing starts from 1) , where Cal(i) calculates the last index encountered which is not co-prime to A[i] while travelling left from i. If no such index is found , then 0 is returned.
Let A[] = 2 3 5 4 9 5 10 , then Cal(i) for i=1,...7 will be 0,0,0,1,2,3,6.


Dp[] = 1 2 3 3 3 3 1

Ans=max(Dp)=3

How to calculate the Cal(i) efficiently ?

A number is not co-prime to another number if there exist a common gcd [ or a common prime factor ].

Ok, then we need to factorise A[i+1] , let say we wrote A[i+1] = p1e1 * p2e2 * p3e3 * .... * pkek , where pi is prime number.

Now we need to pick up the latest index where any of these factors came.

But how can we do it efficiently ?

Look at the constraints and you will notice that A[i] <= 106 , so each prime is less than 106

We can use an array of size 106{let's call it P[]} to find out the latest position. Look at the pseudo code for Cal(i).

Pseudo Code int Cal(int idx) int ret_val = 0 Factors = Factorise(A[idx]) //Factorise will only return prime factors for(int i = 0 ;i< Factors.size() ;i++ ) //iterating through all factors ret_val = max( ret_val , P[Factors[i]] ) //P is an array of size 106 P[Factors[i]] = idx //latest index for prime number Factors[i] is updated to idx. return ret_val

What will be our answer ?

Max ( dp[i] ) for all i

Some PitFalls

You need to precompute factors of each numbers [ from 1 to 106 ]. Reason : Calculating it in run time may lead to TLE because : For factoring any number , you need to iterate over all prime numbers less than sqrt(number). In worst case this number is close to 150. Hence total number of steps will be approximately 150 * 100000 for each Test case. So, for 50 test cases this goes to 75 * 107 which will time out.

Another Way of understanding the Solution
Actually you can also interpret the solution as an application of two pointer method.

Two pointer method
Assume that [i, j] is the your current valid segment/ window. If you go from i to i + 1, and the segment [i + 1, j] still remains a valid segment, then you can apply this method. So you can consider that when going from left to right, if you maintain a pointer for the right end of the good segment, then the right end of the segment always keeps on increasing.

Basically in other words, you can treat the segment as a window representing a valid solution. You need to support fast addition and deletion of elements from the window. But you will notice that if your right pointer always increases then you will never need to delete the right end of the segment. You will always delete the left end and will always add the right end of the segment.

It is very easy to prove that complexity of this method is O(n), as that right pointer is always increasing and hence can make at most n iterations, So overall there could be at most n + n iterations over both left and right ends of a good segment which amounts to total O(n) operations. This method is called window two pointer method.

Sometimes this method is called sliding window algorithm too.

How to apply it in our problem
You can notice that if the segment [i, j] is a valid segment (ie. a segment containing numbers having their lcm equal to their product), then the segment [i + 1, j] is also valid. When we want to extend the right end of our current segment (ie. we are looking at validity of segment [i, j + 1] considering that we know that segment [i, j] is valid), we need to check whether the current number has any common divisor (prime divisor will also work) with any number in the window. This check can be done easily by using the Cal array as explained above.

Overall complexity of this method is O(N).

AUTHOR'S and TESTER'S SOLUTIONS:

Author's solutionTester's solution

TLG - Editorial

$
0
0

PROBLEM LINK:

Practice

Author:ADMIN

Editorialist:SUSHANT AGARWAL

DIFFICULTY:

EASY

PREREQUISITES:

Basic looping,Arrays

PROBLEM:

At the end of each round the leader and her current lead are calculated. Once all the rounds are over the player who had the maximum lead at the end of any round in the game is declared the winner.

EXPLANATION:

Create two arrays(Player1-Stores the scores of player 1 in all the rounds)[a1,a2,a3....an] and (Player2-Stores the scores of player 2 in all the rounds)[b1,b2,b3...bn].

Create a third array "Lead" such that the i'th element of Lead is ((a1+a2...+ai) - (b1+b2...bi)). Create a fourth array "modulus lead" such that the i'th element of this array is the modulus of the i'th element of "Lead".

Find the maximum element of "modulus lead".This is the maximum lead attained by the winner.If the element in the corresponding position of "lead" is positive then player 1 is the winner,otherwise player 2 is.

EDITORIALIST'S SOLUTION:

Editorialist's solution can be found here.

COOLING - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

EASY

EXPLANATION

The following greedy algorithm always finds the optimum answer:

  • Choose the lightest pie not yet on a rack

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

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

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

TESTER'S SOLUTION

Can be found here.

Team Contests

$
0
0

Can users of one team log in 3 systems and submit solutions from different IP addresses. If it is possible which of the submissions are considered, if all the team members submit the solution to a problem?

Viewing all 39796 articles
Browse latest View live


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