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

UNABLE-editorial

$
0
0

PROBLEM LINK:

Practice

Author:Arjun Bharat
Tester:Arjun Bharat
Editorialist:Arjun Bharat

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Hashing, implementation

PROBLEM:

Given a string of length n consisting of only lowercase characters, subject to m pairwise character interchange operations, obtain the final state of the message.

QUICK EXPLANATION:

It suffices to apply the interchange operation on the identity alphabet string, "abcdefghijklmnopqrstuvwxyz".
This is because each original character of the alphabet is always mapped to the index corresponding to it's ASCII value in the identity string(eg. c is mapped to ASCII(c)-97=index 2).
Thus replacement operations are O(m) and the final printing operation is O(n).

EXPLANATION:

A sample snippet of the code used is shown below: //Replacement operation coded in cpp14
for(i=1;i<=m;i++)
{
char p,q;
cin>>p>>q;
for(j=0;j<26;j++)
{
//a denotes the alphabet string, abcdefghijklmnopqrstuvwxyz
if(a[j]==p)
a[j]=q;
else if(a[j]==q)
a[j]=p;
}
for(i=0;i < n;i++)
printf("%c",a[message[i]-97]);
To print the string we print the character at the index of it's mapping in the alphabet string, since the index to which every character of the alphabet is mapped is an invariant.

ALTERNATIVE SOLUTION:

Brute force would apply each interchange operation on the original string,which is O(nm) in overall complexity. This is not feasible given the program constraints.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here: jdoodle.com/a/wQx


recurrence relation with offset techinique

$
0
0

A recurrence relation of this type: $F_n = 2F_{n - 1} + 3F_{n - 2} + 3$ , where sum of the coefficient of recurring terms on both side of the equation is not equal.

I have seen a codechef video ( by Kevin ) where they explain the offset adding to solve this type of recurrence by removal of the constant term. The recurrence can be converted to $G_n = 2G_{n-1} + 3G_{n-2}$ and later use matrix exponentiation to solve it with matrix $\begin{bmatrix} 2&3\\ 1&0\\ \end{bmatrix}$ to obtain the value of $G_n \textit{ mod }M$. For example,

$\begin{align*} &\text{Let, }F_n = G_n + C\\ &\Rightarrow G_n + C = 2\left [ G_{n - 1} + C \right ] + 3\left [ G_{n - 2} + C \right ] + 3 \\ &\Rightarrow G_n + C = 2G_{n - 1} + 3G_{n - 2} + 5C + 3 \\ &\Rightarrow G_n= 2G_{n - 1} + 3G_{n - 2} + 4C + 3 \\ &\Rightarrow C = -\frac{3}{4} \\ \end{align*}$

Now after calculating the value of $G_n \textit{ mod }M$ how to recover $F_n$?

Thanks!

Good permutations

GOSTONES-editorial

$
0
0

PROBLEM LINK:

Practice

Author:sriram10
Tester:sriram10
Editorialist:sriram10

DIFFICULTY:

MEDIUM

PREREQUISITES:

Graphs, depth first search (DFS), topological sort, dynamic programming (DP)

EXPLANATION:

Firstly, if there is a cycle, then the answer would be arbitrarily large, as you could keep returning to a particular vertex and collect stones of the same colour. To find if a cycle exists, you can run a DFS on the graph.

Otherwise, the graph becomes a Directed Acyclic Graph. Now, we compute the maximum score by using DP. We first topologically sort the vertices. The DP is computed this way: Let $DP[i][j]$ indicate the maximum score when the player starts from $i^{th}$ vertex and collects the stones of colour code $j$. Now, if $i$ has no outgoing vertex, i.e. it is the leaf of topological sort, then $DP[i][a[i]]=1$ and $DP[i][j]=0$ for $j!=a[i]$. For all other nodes, $DP[i][j]=max(DP[v][j])$ for all $v$ adjacent to $i$, for every colour $j$. Also, we need to increment $DP[i][a[i]]$ by 1 after the previous process is done. Later, we could print the highest value in the DP table.

AUTHOR'S SOLUTION:

Author's solution can be found here.

TOPTWO-editorial

$
0
0

PROBLEM LINK:

Practice

Author:shay_gan
Tester:shay_gan
Editorialist:shay_gan

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Modular arithmetic

EXPLANATION:

The question is actually deceptively easy. If we have $M$ lanes and $M^K$ horses, finding the top two requires the following steps.

  1. Finding the fastest horse.
  2. Finding the $2^{nd}$ fastest.

Since unless we know the fastest, we cannot find the $2^{nd}$ fastest, it is seen that the $2^{nd}$ step must necessarily complete after the first. Among $M^K$ horses, finding the fastest is easy - race them $M$ at a time, and the winners move on. Since $M^K$ horses are there and each race eliminates $M-1$ horses (since only one horse moves on), the required number of races for this part is $(M^K-1)/(M-1)$. No race will have less than $M$ horses, so the solution must be optimal. Now for the $2^{nd}$ fastest, we need to compare every horse that came $2^{nd}$ in a race the fastest won. Clearly there will be $K$ such horses. To find the fastest of these we just need $ceiling((K-1)/(M-1))$ races.

So the answer is $(M^K-1)/(M-1) + ceiling((K-1)/(M-1))$.

Note: In general, to implement the ceiling function easily while coding, you can use the fact that $ceiling(x/y) = floor((x-1)/y)+1$.

Code in Python: Due to no limit on integer length, we can directly find the answer and apply modulo $10^9+7$

Code in C++: Must do it stepwise due to storage constraints, but it is faster.

Also, as illustrated in this C++ code, without running the loop to calculate $1+M+M^2+...+M^(k-1)$, you can directly calculate $(M^K-1)/(M-1)$ by calculating the modular inverse of $M-1$ under modulo $10^9+7$ using Fermat’s Little Theorem. Both solutions would pass though.

FAMTREE-editorial

$
0
0

PROBLEM LINK:

Practice

Author:ranjithganesh
Tester:ranjithganesh
Editorialist:ranjithganesh

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Trees, Depth-First Search (DFS)

EXPLANATION:

The family can be viewed as a tree as given in the question and an individual's net worth as the value of the corresponding node. One simple observation that can be made is that if the maximum difference in net worth in the tree is between nodes $u$ and $v$, where $v$ is a descendant of $u$, then $v$ must either be the node with maximum value or minimum value in the subtree of $u$. Since the difference in values is to be considered only among its descendants, DFS can be performed which visits the root of all subtrees using recursion and returns the min-value and max-value of its subtree.

The returned min and max values of its descendants can be used to find the max difference in value with the root of the subtree. The final answer will be the maximum of the calculated value among all the nodes.

AUTHOR'S SOLUTION:

Author's solution can be found here.

TWOTOWER-editorial

$
0
0

PROBLEM LINK:

Practice

Author:sathu19
Tester:sathu19
Editorialist:sathu19

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Dynamic Programming, Binary Search

EXPLANATION:

Consider the arrangement 10, 163, 89, 5, 73, 15, 49. To get the final arrangement in ascending form, we need to move blocks 73, 89, 10 and 163. If you observe carefully the remaining blocks 5, 15 and 49 form an increasing subsequence. In fact, this is the longest increasing subsequence. The minimum number of blocks to be moved to form an ascending arrangement will always be $N$ - (the length of the longest increasing subsequence).

For the descending arrangement, we should find the length of the longest decreasing subsequence. Considering the previous example, the unmoved blocks in the descending arrangement are 163, 89, 73, 15 or 163, 89, 73 , 49. The length of the longest decreasing subsequence is 4, i.e the minimum number of blocks to be moved in this case is 3. Hence, Sriram’s arrangement will be used in this case.

To find the longest increasing/decreasing subsequence it takes time complexity $O(N^2)$ through the dynamic programming solution. Since $N$ can go upto $10^5$, a solution with this approach would not pass within the given time limit of 1 second. However, we only require the length of the longest increasing/decreasing subsequence. Finding the length of the longest increasing/decreasing subsequence takes time complexity $O(Nlog(N))$. Please refer to this link for the algorithm to find the length of the longest increasing subsequence. To find the length of the longest decreasing subsequence, we just reverse the array and apply the above algorithm again.

AUTHOR'S SOLUTION:

Author's solution can be found here.

Seg trees GSS1 SPOJ Runtime error


Unfair Codechef Ratings

$
0
0

So due to some small mistake a while ago when my rating was dropped by around 500 points for plagiarism in a really old contest, I didnt say anything. I gave the June Long Challenge and to my surprise, despite having 500 points and a ranking of 71, I got an increase of just 200 points, while some other people of my college, some having solved only 2 questions got a boost of 175 points. Is there any basis behind this? What's the point of a lower rated person even solving the questions in long challenges then? Someone please look into this as I am not the only one pissed off by this.

Getting Runtime Error

quickmatch 10 coming soon with 3 hiring companies

$
0
0

This time we have 3 hiring companies and good ones, good coders working in them...

Will update details once problems are ready. Readying it. https://www.codechef.com/KQ102018

Edit: Codechef to share 250 laddus to top contestants (number of tops depends on number of participants). Thank you codechef.

Cancelling contest, I made mistakes in tests and judging mechanism. Possibly I might end contest hosting here after such grievous mistakes, one person is not enough. I know I will make mistakes again and bring down reputation of cc.

Edit: Thanks for all your encouragements.

I have tester now.... A good news machine learning startup is impressed. Says will hire for 2 positions when some project starts.

Big company wanted exp 1 yr but later said if good uni will do. But now want exp only.

.net will ask however .net one isnt that good. ML one is very good. Dont want to send to .net place. Lets see what happens. I will need hr too.. there might be error in this too.

Invitation to CodeChef June Cook-Off 2018 sponsored by ShareChat!

$
0
0

Hello CodeChef Community!

We’re happy to present to you another fresh set of challenges for your coding skills with the June Cook-Off 2018 sponsored by ShareChat. In addition, there are some exciting job/internship opportunities by ShareChat in the June Cook-Off 2018. More details on the June Cook-Off contest page here: COOK95 Looking forward to seeing your participation in yet another exciting monthly contest! Joining me this time on the problem setting panel are:

  • Problem Setter: barenuz (Igor Barenblat)
  • Problem Tester: mgch (Misha Chorniy)
  • Admin: kingofnumbers (Hasan Jaddouh)
  • Problem Editorialist: vijju123 (Abhishek Pandey)
  • Statement Verifier: xellos0 (Jakub Safin)
  • Russian Translator: xcwgf666 (Sergey Kulik)
  • Mandarin Translator: huzecong (Hu Zecong)
  • Vietnamese Translator: (VNOI Team)

Contest Details:

Time: 17th June 2018 (2130 hrs) to 18th June 2018 (0000 hrs). (Indian Standard Time — +5:30 GMT) — Check your timezone.

Contest link:https://www.codechef.com/COOK95

Registration: You just need to have a CodeChef handle to participate. For all those, who are interested and do not have a CodeChef handle, are requested to register in order to participate.

Prizes: Top 10 performers in Global and Indian category will get CodeChef laddus, with which the winners can claim cool CodeChef goodies. Know more here: https://discuss.codechef.com/questions/51999/how-do-i-win-a-codechef-goodie. (For those who have not yet got their previous winning, please send an email to winners@codechef.com)

Good Luck!
Hope to see you participating! Happy Programming!

No reply from CodeChef

$
0
0

Hello,

I received an email from CodeChef on 31st May 2018 stating that my code matched with another user in the May Long Challenge 2018. I mailed back the same day, so did the person who had copied my code confessing to the same. Till now, I've not been informed whether the plagiarism case against me has been dropped or not.

I'd request someone from the CodeChef officials to please update me on the status of my case.

Thank you

CHEFGR-Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Dmytro Berezin
Tester:Jingbo Shang
Editorialist:Ajay K. Verma

DIFFICULTY:

Cakewalk

PREREQUISITES:

ad-hoc, basic math

PROBLEM:

Given an array of positive integers, determine if it is possible to make all the elements in the array equal by adding non-negative number to its elements such that the sum of the added numbers is exactly M.

EXPLANATION:

For the given array A of size N, we want to determine whether it is possible to make all its elements equal by adding non-negative numbers to them. Let as assume that it is possible to do so and the final value of the elements is x.

This means the following two conditions must hold:
1) x >= A[i], for all i, and
2) sum of (x - A[i]) is M.

From the second condition, we can actually compute the value of x:
(x - A[1]) + (x - A[2]) + ... + (x - A[N]) = M
x = (M + A[1] + A[2] + ... + A[N]) / N

If x is not an integer, then clearly we do not have a solution. Hence, we need to check the following two conditions for the existence of a valid x:
1) (M + A[1] + A[2] + ... + A[N]) must be divisible by N,
2) None of the elements of the array should exceed x = (M + A[1] + A[2] + ... + A[N]) / N.
3) The x must hold : x>= max(A[i]) of the original array. So that all array elements become equal in the end.

Time Complexity:

O (N)

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution will be put up soon.
Tester's solution will be put up soon.

Doubt with AMSGAME1


Are we really competing against someone in 'CodeArena' of Hackerearth?

$
0
0

I've recently started participating in the 'CodeArena' 1-to-1 fight. However, not a single opponent has ever managed to submit even a partially correct solution in any of the fights I've participated in.

Some days ago, while ‘fighting', I saw my opponent compiling his code and then submitting it only to get a WA in all the test cases. The problem was far too easy to get a WA. I tried to locate his submission after the fight, but couldn't find it.

My suspicion increased when I looked into their profiles. All of them "hasn't added any details yet." Each profile name has the syntax: <first_name><dot><last_name>, sometimes followed by another <dot> and/or a random number.

Eg. Yesterday, I fought against someone called Niranjan Kumar (@niranjan.kumar1).">https://www.hackerearth.com/@niranjan.kumar1). Problem was Choosing the Judges; a standard DP problem. My opponent compiled his code, then submitted, and obviously got a WA.

alt text

After contest ends, I find the problem, view the "All submissions" page and.... Wow, my opponent is non-existent.

alt text

I admit I am new in Hackerearth, and I must not bluntly accuse someone; but am I really missing anything?

SUBINC - Editorial

$
0
0

Problem Link

Practice
Contest

Difficulty

Simple

Pre-requisites

Simple dynamic programming

Problem

Count the number of non-decreasing subarrays of the given array A[].

How to get 20 points

Let's choose the left bound, say L. After the left bound is fixed, let's choose the right bound, say R. And now, let's check that the subarray A[L, R] is non-decreasing.

In other words, let's iterate through all possible subarrays and then, for each of them, check whether it is a non-descreasing one or not.

Choosing the left bound takes O(N) operations, choosing the right bound takes O(N) operations too, and checking subarray also takes O(N) operations. Since these operations are nested, hence the total complexity will be O(N3).

This solution is good enough to solve the first subtask.

How to get 50 points

Let's choose the left bound, say L. Let the right bound, say R, be equal to L initially. Then while the elements are non-decreasing keep increasing the right bound R. At some moment, you will certainly stop. The amount of non-decreasing subarrays with the left bound at L will be equal to R-L+1 for every fixed L. The sum of all this values is the answer to the problem.

Choosing the left bound takes O(N) operations, and finding the right bound takes O(N) operations. Since these operations are nested, the complexity of the whole solution will be O(N2).

This solution solves the first and the second subtask, but is still not good enough to get the full points.

How to get 100 points

Let's introduce an array B[] of N elements, where the ith element of B[] defines the amount of the correct subarrays with the right bound equal to i.

Now, let's give the rules for calculating the ith element of B[]:

  • if A[i-1] ≤ A[i], then B[i] = B[i-1] + 1 since every non-decreasing subarray that ends at the (i-1)th element can be continued with the ith element without loss of non-decreasingness and one more non-decreasing subarray that ends at the ith element is A[i, i].
  • if A[i-1] > A[i], then B[i] = 1 since any subarray that ends at the (i-1)th element will lose its' non-decreasingness if continued with the ith element, so the only suitable subarray will be A[i, i].

So, the answer will be equal to the sum of all elements of B[]. The complexity is O(N), because the computation of the array B turns out to be a single for-loop with a condition for the computation of B[i] inside.

Setter's Solution

Can be found here

Tester's Solution

Can be found here

Please someone help me for solving this problem.

[June Cook-Off 2k18] Is this a valid algorithm/approach to solve Good Permutations Problem ?

$
0
0

Hello, I was trying to solve the 2nd most solved problem in the June cook-off 2k18 contest, even though I believe my approach is valid however still i would like to seek your review and suggest me any better approach or flaw in my existing approach, I will not be posting entire code but just basic algorithmic idea. My code isn't getting accepted (WA) probably due to side cases, and since I urgently want to know the validity of my approach I'm posting it here.

APPROACH (for the single test case)

  1. input N, K
  2. input an array ARR of size N
  3. scan the ARR for 0s and create another array "indices" that will store index i , where ARR[i] is 0
  4. replace 0s in ARR by unused numbers ( for example [2,0,0] becomes [2,1,3] ) (I'm not going into detail of how this is done)
  5. Permute the array "ARR" for only those indices where 0 was replaced by another value using the call to the method given below

https://ideone.com/s9eeax

here, in the first ever call to permute, beg = 0 and end = ind.size()-1 where k is mentioned in the problem statement of the question. Time complexity of the permute method is O(N^2 * fact(N))

If in case anyone is interested to check out entire code for further detail, please check this out https://www.codechef.com/viewsolution/18947214

If the algorithm is not clear please do let me know so I can write it more clearly.

BINSHFFL : Codechef giving WA

$
0
0
enter code here
#include <iostream>

using namespace std;

int countDigits(long long a){ int count=0; while(a){ a=(a&(a-1)); count++; } return count;

}

int main(){ ios_base::sync_with_stdio(false);

int T;
cin>>T;
while(T--){
    long long A,B;
    cin>>A>>B;
    int ans;
    if(B==0){
        ans=-1;

    }
    else if(B==1 ){
        if(A==0)
        ans=1;

        else{
            ans=-1;

        }
    }
   else if(A==B){
        ans=0;

    }
    else{
        int digitsA=countDigits(A);
        int digitsB=countDigits(B-1);
        //cout<<"Digit A:"<<digitsA;
        //cout<<"Digit b:"<<digitsB;
        //cout<<endl;

        if(digitsB<digitsA)
        ans=2;
        else
        ans=digitsB-digitsA+1;

    }
    cout<<ans<<'\n';
}

}

Please look into solution. I am getting WA. Unable to resolve error

Viewing all 40121 articles
Browse latest View live


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