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

Corner Cases in "Coloring the Grid" (Oct LunchT 2018)??

$
0
0

Coloring the grid (LTIME65B)

Can some help me in finding whats going wrong with my logic for the above question
it gaved AC for sub task-1 but went wrong for the last testcase of the sub task-2

My Solution : https://www.codechef.com/LTIME65B/status/CLORGIRD,tushar2899
for those who are unable to access:


num1=int(input())
for _ in range(num1):
    num2=map(int,raw_input().strip().split())
    k=[]
    for j in range(num2[0]):
        l=raw_input()
        k.append(l)
    pri=0
    for i in range(num2[0]):
        temp=0
        for layer in k[i]:
            if layer=='#' and temp==1:
                pri=1
                break
            elif layer=='.':
                temp+=1
            else:
                temp=0
        if temp==1 or pri==1:
            pri=1
            break
    if pri==0:
        for stand in range(num21):
            temp=0
            for ls in range(num2[0]):
                if k[ls][stand]=='#' and temp==1:
                    pri=1
                    break
                elif k[ls][stand]=='.':
                    temp+=1
                else:
                    temp=0
            if temp==1 or pri==1:
                pri=1
                break
        if pri==0:
            print "YES"
        else:
            print "NO"
    else:
        print "NO"


ANCESTOR problem

$
0
0

problem : ANCESTOR i actually thought about ->traversing down the both the trees parallely from root to leaves and binary lifting of the bfs/dfs array..... can anyone share his approach..?

fibonacci modified

THREEFR - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Praveen Dhinwa
Tester:Teja Vardhan Reddy
Editorialist:Taranpreet Singh

DIFFICULTY:

Cakewalk

PREREQUISITES:

Basic Math and Linear Equations.

PROBLEM:

There are three friends $A$, $B$ and $C$. They make the following claim.

  • A says that I have $x$ Rupees more than B.
  • B says that I have $y$ Rupees more than C.
  • C says that I have $z$ Rupees more than A.

Given $|x|$, $|y|$ and $|z|$, Find out if it's possible to assign signs to $x$, $y$ and $z$ so that all three claims hold.

SUPER QUICK EXPLANATION

  • Answer is yes if and only if $|x|+|y|+|z| = 2*max(|x|, |y|, |z|)$.

EXPLANATION

Suppose Friend A has $a$ Rupees, B has $b$ Rupees and C has $c$ rupees. Then, the three claims result in the following equations.

  1. $a = b+x$
  2. $b = c+y$
  3. $c = a+z$

Substituting value of $a$ from 1 in 3, we get $c = (b+x)+z$.

Substituting value of $b$ from 2 in this equation, we get $c = (c+y)+x+z$.

We have the final equation $x+y+z = 0$.

Two solutions exist.

One is to try every combination of signs for $x$, $y$ and $z$ and checking if it satisfies above relation at any time. It may take $8$ ($2^3$) iterations in the worst case.

Other is to notice that the two values other than largest have to be assigned the same direction, while the largest value will be assigned opposite direction, to get sum $0$.

See, if we assign a value other than largest value, same sign as largest, we can never get the sum $0$ by assigning whichever sign to the third element. So, assign smaller two elements one direction, and largest value opposite direction and print Yes if the sum is $0$. Otherwise, print No.

Time Complexity

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

AUTHOR'S AND TESTER'S SOLUTIONS:

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

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

ROBAGAIN - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Jatin Yadav and Praveen Dhinwa
Tester:Teja Vardhan Reddy
Editorialist:Taranpreet Singh

DIFFICULTY:

Medium

PREREQUISITES:

Observations, 2-satisfactability and Simulation.

PROBLEM:

Given a field of length $N$ with some robots having range $d$ implying they can move anywhere in the range $p-d, p+d$ if within the field, one step at a time, Can we assign directions to each of the robots in such a manner that none of the robots collide. You can assume that the robot once reaching either end of their range, will flip their direction and continue moving and they continue to move till the end of the universe. :P

EXPLANATION:

Once again, I will be sharing two solutions, one intended, and another one as usual mine. :P (Seems like this is happening a lot with me xD). SOLUTION 1 is my solution, while SOLUTION 2 is intended one. So, here you go.

SOLUTION 1:

Observations: * If two robots at time 0 have odd distance, they can never be at the same position ever Because both of them keep moving at same pace. So, Solve this problem assuming each robot have even distance from all others. See, Since each robot move by one step in either direction once step, then parity of position of each robot flip after every second. The only exception is robots with range 0, which remain at their position always. Assume 0 range robots don't exist for now.

  • Since all robots have even distance, they can never cross each other without colliding with each other. Thus, all the robots now will preserve their initial ordering always. If two robots try to come near each other, their distance reduces by a factor of 2 every second. The initial distance between them is also even, so it is bound to become 0 before becoming negative. 0 distance implies collision.

With these two observations, we can solve the problem in a much simpler manner. Now, no robot can ever cross each other, which means that any robot, if collide, can only collide with neighboring robots only.

After splitting the robots, we try to assign direction to the current robot, making sure no robot at previous positions collides. We try all four combinations of directions for two robots.

Now, the problem is, how to check if two robots collide. First of all, if their distance is above 20, they can never collide. After that, We can just simulate their movement over $X$ steps. How to decide $X$? $X$ is just the LCM ie Least Common Multiple of path lengths of both robots. Since path lengths $\leq 20$, we can safely take $X = 400$ and run simulation for $X$ steps. If they do collide at the current combination of directions, this combination of direction cannot work. Suppose we get a combination (prev, cur) such that it is possible to assign "prev" direction to previous robots without collision, and this combination does not cause a collision, then the current robot can be assigned "cur" direction.

This way, valid assignment exists if and only if all robots have a direction which they can be assigned, without causing a collision.

Now, considering robots of range 0. They never move, thus dividing the whole range into parts, one to the left and other to the right. We can simply check, if any other robot's range includes the current position of any 0 range robot, it will collide with the current robot no matter what direction they are assigned, resulting in an unsafe assignment.

SOLUTION 2:

For this solution, readers should be aware of 2-satisfiability which you may read here.

Since checking the existence of valid assignment is pretty simple if we get the implication graph, I will be talking mostly about Construction of Implication graph.

Keep one variable for each robot in the graph. Variable value false means robot is assigned direction left, while value True means variable is assigned direction left.

For every pair of the robot, which are near (meaning having distance less than 20), we check by simulation if they ever collide for all four combinations of directions. If they collide, we add a directed edge in implication graph.

For example, suppose if robot 1 (denoted by variable R1) and robot 2 (denoted by R2) collide, if they are assigned direction (left, right), then we add to graph an edge !R1 implies !R2 (read R1 bar implies R2 bar).

This way, we have the implication graph ready, now just run the standard SCC algorithm to get all strongly connected components. If we have R1 and !R1 in the same SCC, There doesn't exist any valid assignment of direction, hence unsafe. Otherwise, It can be proven that the valid assignment always exists. (SOLUTION 1 also gets the assignment in the process).

Time Complexity

For solution 1, the time complexity is $O(N)$ with a constant factor.

For solution 2, The number of edges is bounded by a factor of N, and the time complexity is just the time taken to add edges to graph and finding SCCs which take $O(V+E)$ time, Overall Time complexity is $O(N)$.

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

No response from bugs@codechef.com for my bug report.

$
0
0

Dear @admin,

I have found a vulnerability on codechef and reported it to bugs@codechef.com as per the codechef bug bounty guidelines but they don't give any reply to me now what should I will do please help me.

I have reported bug 2 days a go and bug is still not fixed it can be serious issue if bug not get fixed.

CTOUR - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Abhineet ShrivastavaIshank Bhardwaj 

Tester:Ishank Bhardwaj

Editorialist:Abhineet Shrivastava

DIFFICULTY:

MEDIUM-HARD 

PREREQUISITES:

Least Common Ancestor, DP, Graphs

PROBLEM:

Given a rooted tree with N nodes and Q queries. In each query, two nodes A and B are given. The problem is to calculate path from node A to node B using a special traversal. In the traversal from node A to node B, you can reverse your direction only once. Reversing the direction means earlier the you were going towards the root, then away from the root or vice versa.

EXPLANATION:

The problem can be solved using LCA and dp on trees.

Pre-processing steps:

  1. Profit from root to all the nodes - profit[n].

  2. For calculating LCA in log(n).

  3. Using DP on trees, calculate the max profit for each node, if we are at the node and go towards the root and come back - up[n].

  4. Using DP on trees calculate the max profit for each node, if we are at the node and go towards downwards and come back - down[n].

Calculation steps:

Every query can be answered in O(log(n)).

There are three cases.

  1. If LCA (A, B)!= A or B. Then we have only one choice- going from A to LCA(A,B), then towards root to some extent and then to B. The total amount we can gain is profit[A] + profit[B] - 2 * profit[LCA(A, B)] + 2 * up[LCA(A, B)].

  2. If LCA(A, B) = A. Then we have two choices- going upwards from A and back, or going downwards from B and back. The total amount we can gain is profit[B] - profit[A] + 2 * max(up[A], down[B]).

  3. If LCA(A, B) = B. Then we have two choices- going upwards from B and back, or going downwards from A and back. The total amount we can gain is profit[A] - profit[B] + 2 * max(up[B], down[A]).

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here

Tester's solution can be found here

dynamic programing


CHEFADD - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest

Setter:Misha Chorniy
Tester:Hasan Jaddouh
Editorialist:Taranpreet Singh

DIFFICULTY:

Easy-Medium

PREREQUISITES:

Bitwise operation, Dynammic Programming.

PROBLEM:

Given three numbers $A$, $B$ and $C$, given $A+B = C$, We can change positions of bits in $A$ as well as in $B$. Calculate Number of ways we can do so, such that their sum is $C$.

SUPER QUICK EXPLANATION

  • Solve the problem in increasing order of bits, handling carry forward carefully.
  • Dynamic Programming state consists of tuple (bit, cntA, cntB, carry), where bit is the bit position, cntA is number of bits of A not yet used, cntB is number of bits of B not yet used, and carry tells whether we have one carry forward from the previous position or not.
  • Final answer is the value of tuple (0, bit(A), bit(B), carry), where bit(X) counts the number of set bits in $X$.

EXPLANATION

This solution seems complicated implementation at first sight, but is actually not, if you are comfortable with Bitwise Operations.

First of all, I am going to share very basic stuff about bitwise addition in secret box.

View Content

Now, we all know, that we $A+B$ should have all bits same as $C$. We need to count the number of ways to shuffle bits. So, we are going to handle problem bit-by-bit.

Important thing is, that If we add two bits at a position, there may be a carry forward to next bit. This means, that bit to be chosen at the next significant position is dependent on carry-forward from the previous position. This means, that we have to approach the bits from least significant bit to most significant bit.

So, Suppose we need to have a bit at current position to be $x$, with carry-forward $cf$ from the previous position.

If $x$ is same as $cf$, We can either have the current bit set in both numbers or none of them. Because if we choose to have set bit in exactly $A$ or $B$ at the current bit, the current bit will get flipped, resulting in $A+B \neq C$.

If $x$ is not same as $y$, we have to flip the current bit, which can be done only if exactly one of the $A$ or $B$ have current bit set, which will lead to flipping the current bit.

If you have understood this much, give it a try.

After doing this much, If you build a simple recursive solution, we would probably get Time Limit Exceeded, since our solution is calculating some values multiple times, resulting in exponential time complexity.

To speed up, you can just notice, that you can build a lookup table ans[bit][cntA][cntB][carry], storing answer for the tuple (bit, cntA, cntB, carry) and instead of calculating it, just look it up from here. This result in reducing time complexity from exponential to polynomial time complexity, sufficiently fast to pass time limit.

A secret box, only for people who do not know Dynamic Programming.

View Content

Editorialist's talk

I was going through some accepted codes for this problem when I found this really nice solution. Have a look. I was looking for an iterative solution to this problem. Anyone having completely iterative solution will be mentioned here. Please share with me the link of code.

EDIT: A completely iterative solution can be seen here, by @pulkit_sja

Time Complexity

As you will commonly find in dynamic programming problems, Actual time complexity depends upon Number of states visited.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution
Tester's solution
Editorialist's solution (Commented)

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

NICARRAY - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Praveen Dhinwa
Tester:Teja Vardhan Reddy
Editorialist:Taranpreet Singh

DIFFICULTY:

Easy

PREREQUISITES:

Backtracking, Combinatorics, and Modular Arithmetic.

PROBLEM:

Given an array $A$ of length $N$ with some elements missing and a value $S$, consider all ways of filling missing elements and for every resulting array, find the sum of gcd of every unordered pair. Print the sum modulo $10^9+7$.

SUPER QUICK EXPLANATION

  • Order of elements does not matter. If $C$ is the number of missing elements in the array and $Si$ is the sum of non-missing elements, We need to fill $C$ values so that their sum is $S-Si$.
  • We can calculate all such ways by forming all ways, say in the array $B$ of length $C$, such that $B[i] \leq B[i+1]$ and counting all different ordering using combinatorics.

EXPLANATION

Considering the slow solution first.

We can make a backtracking solution where we try to fix the first $x$ elements, and filling missing elements with all possible choices such that the total sum does not exceed $S$. Then iterating over every pair of values and calculate pairwise gcd-sum and print the answer. Time complexity, in this case, is Exponential, thus, will pass only the first subtask.

For the second subtask, we need to work harder than that.

First of all, Notice that the order of elements does not matter at all since the position of an element is irrelevant to our problem.

Second thing, If $Si$ is sum of visible elements, Missing elements can have sum $S-Si$. Now, Suppose we have a parititon $B_1, B_2, B_3 \dots B_k$ such that $\sum B[i] = S-Si$.

If we can get all partitions of $S-Si$ into $C$ elements, we can simply calculate the answer in $O(N^2)$ by iterating over every pair and taking gcd.

But, Number of partitions of $S$ is also very high if we consider them ordered. Like, If we consider $1+2$ different than $2+1$ as a partition of $3$, Number of the partition of $50$ is very high.

But, We can notice, that pairwise gcd-sum do not change, when just the ordering of elements of partition changes. Like, Suppose we have example N = 3, S = 4 and array 1 -1 -1. We can notice that pairwise gcd-sum of 1 1 2 is same as pairwise gcd-sum of 1 2 1. Hence, if we can calculate the pairwise gcd-sum for all distinct partitions of $S-Si$ with non-missing elements, we can solve this problem fast enough.

Now, we can once again use backtracking solution, this time with another constraint, that current element cannot be smaller than the previous element. This way, we can get a partition and we calculate pairwise gcd-sum.

But, the problem is, how do we know how many times a partition will appear. Fortunately, we can rush to Combinatorics :P for answers. We can see, It is just the number of Distinct permutations of the given sequence.

Fortunately, If any element occurs $x$ times, the Same permutation will be counted $x$ times. This way, We can just Find the number of distinct permutations of the given sequence, and thus, find the required answer.

Hence, we can just find every unordered partition of $S-Si$ into $C$ elements, Find pairwise gcd-sum with each partition and also the number of times the same partition may appear and calculate the answer.

For reference, the method of computing distinct permutations of a sequence can be found here.

Time Complexity

The time complexity of this solution is $O(P(S)*N^2)$ where $P(S)$ is the number of unordered partitions of $S$. There is no closed form for Number of unordered partitions of a number, but for $S = 50$, it is small enough for our solution to pass comfortably.

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

WEIRD2 - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Hasan Jaddouh
Tester:Teja Vardhan Reddy
Editorialist:Taranpreet Singh

DIFFICULTY:

Easy-Medium

PREREQUISITES:

Observation, Amortized analysis and data structures.

PROBLEM:

Given an array $A$ of length $N$, find out the number of ordered pairs $(a,b)$ such that $a$ appears at least $b$ times in array while $b$ appears at least $a$ times in the array.

QUICK EXPLANATION

  • Sort the given array, and for every position, iterate over the positions having less than the frequency of current element.
  • Above solution works in overall $O(N)$ time because, at every iteration, we iterate over at most $F[i]$ elements in each iteration where $F[i]$ is the frequency of $A[i]$. Since $\sum F[i] = N$, Overall complexity is $O(N)$.

EXPLANATION

For this problem, I have two solutions to offer, First the intended solution, which is used by Setter and Tester, while the other one is my solution.

Let us make input in form of frequency mapping tuples $(A[i],F[i])$, where $F[i]$ denote frequency of $A[i]$ in input array.

Bruteforce Solution: Iterate over every ordered pair $(i,j)$, $i \leq j$ of values and check if $F[j] \geq A[i]$ and $F[i] \geq A[j]$ holds.

Since we iterate over all pairs of values, this solution has complexity $O(N^2)$.

Now, let us rewrite the conditions of a valid pair. For pair $(A[i], A[j])$ to be valid, we need $F[j] \geq A[i]$ and $F[i] \geq A[j]$.

Let us sort these tuples in increasing order of $A[i]$ and run the same loops as BruteForce. Now, notice, that for any $(A[i], F[i])$, if we get the position $A[j] > F[i]$ for any position $j$, we can safely see, that No position $k$, $k > j$ will satisfy $F[i] \geq A[k]$. Hence, we can break out from internal loop as soon as we reach a value $A[j] > F[i]$.

Now, What is the time complexity of this solution? This is where Amortized Analysis comes into play.

See, For every position, we iterate over at max $F[i]$ element in inner loop. Since $N = \sum F[i]$, The overall solution complexity is bounded by $N$, resulting in overall $O(N*logN)$ solution due to sorting.

Now, Let's discuss Editorialist solution in brief, who didn't get the observation at first.

Make frequency tuples same way as above solution and sort tuples by non-decreasing order of $F[i]$. If we focus on condition $A[i] \leq F[j]$, we know that this condition will hold for a suffix of the array due to the non-decreasing order of $F$. This way, Now we need to count the number of positions in Suffix $[j, N-1]$ for which $A[j] \leq F[i]$. Let's call $(j, F[i])$ a query, and $j$ is the left end of query range, right end being the end of the array.

There exist a more general problem which can be applied here. Given an array of length $N$, Perform two type of operations. First is to update a single element. Other is to count number of elements $ \leq x$ in range $[l, r]$.

Editorialist just uses Order statistic tree, along with sorting queries $(j, F[i])$ by decreasing order of $j$, and answer queries and add elements to order statistic tree as the $j$ decreases, and making queries when the current range of added elements correspond to query range.

The time complexity of this solution too is $O(N*logN)$ but is probably slower than the first solution due to the constant factor.

This was a lesson, that observations matter. :P

Related problem

The problem Tufurama seems a lot similar to this problem, though have quite a different solution which is worth a try.

Also, The problems KQUERY and KQUERY2 are nice problems to practice if you tried the second solution.

Time Complexity

The time complexity of both solutions is $O(N*logN)$ but the first one has lower constant factor than the second solution.

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

SLAEL - Editorial

$
0
0

PROBLEM LINK:

Practice  Contest

Author:Ishank Bhardwaj

Tester:Yash Gulani

Editorialist:Ishank Bhardwaj

DIFFICULTY:

EASY

PROBLEM:

Find the length of the longest contiguous segment in an array, in which if a given element K is inserted, K becomes the second largest element of that subarray.

EXPLANATION:

We can store the index of all the elements which are greater than K in a vector v. If we include the element at position v[i+1] from the array, then the length of this segment is v[i+2]-v[i]-1. The largest element is at position v[i] and we can insert the second largest element anywhere in the range. If all the elements had been distinct, this solution would have been passed.

Since elements can be the same, we just need a small implementation change. We can take a vector of vectors. A vector will store the index of all such elements which are equal and no other element greater than K lies on it. No the ans=max(v[i][first] - v[i-2][last] - 1) over all i. Insert indices -1 as a first vector and n is the last vector to handle edge cases in implementation. This is one way, there might be other better ways also.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here

Tester's solution can be found here.

Robogame help

$
0
0

Could anyone explain what's wrong with this code ? I have run it against 30k test cases and it looks ok.

Tkank you for your explanation.

Here is the code with test cases: https://ideone.com/loGTuM

Server Issues

$
0
0

What has happened to codechef? It regrets the inconvenience caused everytime and still causes inconvenience. I finished all my work as early as i can, so that i can have a crack at snackdown questions before sleeping but the contest has been delayed by 2 hours. Please codechef, start providing tentative timings for contests if you cannot begin contests at the time you've proposed, beforehand.

OLDFAR - Editorial

$
0
0

PROBLEM LINK:

PracticeContest

Author:Yash Gulani

Tester:Ishank Bhardwaj

Editorialist:Ishank Bhardwaj

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Dynamic Programming

PROBLEM:

Given a matrix mat with N rows and M columns, find the maximum sum that can be extracted from it, if we traverse a path, starting from mat[i][N], with 1<=i< N, and taking exactly two left turns, and ending at mat[j][N], with i< j <= N.

EXPLANATION:

The problem can be divided into two parts:

  1. Profit earned in going from given cell to the rightmost cell in shape of 'L'.

  2. Profit earned in coming from rightmost cell to a given cell.

For a matrix “mat” with dimensions NxM,

  1. dp[i][j] represents the maximum sum that can be obtained by traversing a ‘L’ shaped path formed from the coordinates, (i,j), (x,j) and (x,M) where (i=< x< =N) , for the submatrix with top-left corner at i,j and bottom right corner at N,M.

  2. revCum[i][j] represents the sum, mat[i][j]+mat[i][j+1]+mat[i][j+2]...............mat[i][M]

dp[i][j] can be calculated as, dp[i][j] = mat[i][j] + max(dp[i+1][j],revCum[i][j+1]) (Base cases can be handled accordingly)

After the dp and revCum have been calculated, the matrix can then be traversed and answer can be calculated using ans=max(ans, revCum[i][j]+dp[i+1][j])

AUTHOR'S SOLUTION:

Author's solution can be found here.


MINDSUM - Editorial

$
0
0

Problem Link :

Division 1

Division 2

Author : pekempey

Tester : Misha Chorniy

Editorialist : Anand Jaisingh

Pre-Requisites :

Properties of digital roots

Explanation :

Digital Sums and properties of digital sums may be common to some participants. Let's establish $2$ very important properties of digital sums required to solve this problem.

Let $Dr(x)$ be a function defined for integer $x$ as :

$Dr(x)= x, $ if $ 0 \le x \le 9 $,

else

$Dr(x)=Dr(Sum-of-digits(x))$

This function $Dr(x)$ is called the digital root of a number $x$. Now,

$Dr(a+b) = Dr(Dr(a)+Dr(b))$,

$Dr(ab) = Dr(Dr(a)\cdot Dr(b)) $

These are well known properties, and you can find proofs of them here. It is very clear that the minimum value we are trying to find is a single digit number.

Claim 1 : : The minimum value is always the minimum over : $ Dr(N+kD)$ for some non-negative integer $k$.

Proof :

$ Dr(N+kD)=Dr(Dr(N)+Dr(kD)) ... (1) $

Now, $Dr(kd) = Dr(Dr(k) \cdot Dr(D)) $.

Possible values of $Dr(k)$ are $ 0,1,2...9 $ , given by numbers $ k=0,1,2...9 $

Now, $Dr(x)=Dr(Sum-of-digits(x)) ... (2) $

So, the minimum value for $N$ is obviously equal to the minimum value for $Sum-of-digits(N)$. Reducing the answer once and then adding $D$ does not affect the minimum possible value that can be reached. If any any place, we have a reduce operation followed by an add operation, the we can do the add operation and then the reduce operation without affecting the possible roots we can reach. This is proved as a combination of formulae $(1)$ and $(2) $

Doing a reduce operation followed by an add operation can be replaced by doing an add operation followed any further operations and we can still reach the same set of roots. In short, we can do all add operations first, all reduce operations later, and reach any number that can be possibly reached by any set of operations

So, using these two claims, we can prove the minimum possible value is the minimum of $Dr(N+kD) $ where $ 0 \le k \le 9 $

Now, to find the minimum number of steps, we must first note that the relative order of the add and Sum-of-digits operations does affect the answer. However, we can note that the Sum-of-digits function is an extremely fast decreasing function.

Any number $ \le 10^{10}$ goes to a number $ \le 90$, any number $ \le 90 $ goes to something $ \le 18 $ and so on. In short , any number can be reduced to its digital root in $ \le 3-5 $ steps.

Via this, we can prove that the value of the minimum steps can never be greater than $15$. This is a loose upper bound, not the exact one. Let's prove this via contradiction : If some process takes $ > 15 $ steps, we can always take $N$ to the value of $N+kD, k \le 9 $ that provides the minimum possible value, and then reduce it in $5-6$ steps. Using this fact, we can now in-fact construct a brute force algorithm.

We can follow a complete brute force recursion algorithm, that at each step branches in $2$ different directions, one $x=Sum-of-digits(x)$, the other being $x=x+D$, but only until a recursion depth of $15$. In this way, we stop after exploring $2^{15}$ different ways.

After reading all proofs mentioned above, understanding the code should be trivial. Also note that the greedy nature of this problem permits many other solutions too, and you can read about some of them using the comments below.

Overall time complexity $ O(T \cdot 2^{15} \cdot log_{10} N ) $

Tester's Code : : Link

My Code : : Link

[UPDATE]Chrome web store now has Coding shout

$
0
0

Frustrated of staring at your screen waiting for the result of your submissions to pop up? Relax and read the next problem while this extension checks the result continuously and notifies you as soon as the results appear. It uses text to speech to say the result, or if you prefer being silently notified, there is an option for that too.

Supported judges:

  • Codechef
  • Codeforces
  • AtCoder Beta

Chrome

Firefox

Github

I will be adding it to Chrome Web Store in the next few weeks, so stay tuned for that! For now you can follow the instructions given on Github to install for Chrome and don't forget to leave some stars on Github.

PS: It is about a second faster than the submission page.

ACM-ICPC online round

$
0
0

Thanks for the 1st speed test problem and a bullshit problemset.thanks.you people will realize what sort of bullshit teams will now come to regionals.thanks.

The problem setter just showed boasted his experience.

Thanks for bullshit problemset.

AND NO NEED TO POST INTELLECTUAL REPLIES IN COMMENTS.

LAST 2 YEARS TEAMS CHEATED YOU DIDN'T DO ANYTHING.(in rated contests you people are the first who dropped ratings without hearing the sufferer,you say you saw the email,thats pure lol).

YOU DON'T EVEN MAKE CODE PUBLIC.

THIS YEAR TEAMS ADVANCED VIA SINGLE PROBLEM(SPEED TEST).

TO THE TEAMS OUT THERE EXCEPT THOSE WHO SOLVED 2ND PROBLEM "YOU ARE BS TEAMS.YOU WON A SPEED TEST".

2 Accepted Solution giving 2 different outputs - SLAEL , ENCO2018

$
0
0

Link to the Problem - CLICK HERE

For Test CASE:

1

8 4

2 6 2 2 5 2 2 2

The Correct OUTPUT is 6 but the AC solution this gives OUTPUT 4 where as some other AC solutions gives OUTPUT 6 like this.

First i have written this which gives 6 OUTPUT but this got WA.

Then after observing AC solution I have edited my code to this which gives OUTPUT 4 and this got AC. How can we trust these questions. This question have ruined my competition and many other competitor.

Help in solving Palindromic Queries from snck15el

$
0
0

I was trying to solve the problem ANKPAL | Palindromic Queries, I have seen the editorial for this problem but editorial doesn't have enough implementation details for hashing. After that I have looked at couple of solutions, but I couldn't figure out how hashing is working there. Can anyone please help me with this?

Viewing all 40121 articles
Browse latest View live


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