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

ALEXTASK - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

DIFFICULTY:

Simple

PREREQUISITES:

LCM, basic programming skills

PROBLEM:

You are given N events, the i-th event will occur every Ai-th milliseconds. Find the first millisecond when at least two events is happening at that millisection.

EXPLANATION:

First subtask

A very straight forward way to solve this problem is to check for every millisection starting from the first millisecond whether at least two events will occur on that millisecond or not, we stop at the first millisecond in which at least 2 events occured at this millisecond and this will be the answer.

For example, let's say in the first millisecond one event will occur then we go to check the second millisecond and let's say no events happened then we go and check the third millisecond and for example 4 events will occur in that millisecond then we stop and the answer is 3.

but how to calculate the number of events which will occur in a particular millisecond (say x-th millisecond )? since i-th event will only occur in the milliseconds which are divisible by Ai then we should count the number of tasks in which x mod Ai = 0

so for each millisecond, we should iterate over the array A with a loop and keep a counter to the number of milliseconds which are divisible by the current millisecond, after that we check the counter, if it's bigger than 1 then the answer is the current millisecond, otherwise we go and check the next day.

the complexity for this solution is O(N*answer), unfortunately since the answer can be large so this solution will not get full marks.

full solution

Since the required millisecond can be large then we need to find an idea that does not iterate over the milliseconds one by one.

One idea is to try to find a way that immediately calculate for a particular pair of events the first millisecond in which those two events will both occur in that millisecond, other events might also be by coincidence occur on that millisecond but that doesn't matter us. if we find such a way then we just iterate through all pairs of events and apply that way on them then we select the minimum millisecond among all pairs.

now, given two events what is the first millisecond in which both tasks will occur? let's say the indices of those two tasks are i and j, then such a millisecond must be multiple of both Ai and Aj, among all such milliseconds we should pick the minimum millisecond so we just need to calculate the least common multiple (LCM) of Ai and Aj and this will be the answer for this particular pair of tasks.

now let's explain how to calculate LCM of two numbers (say A and B), there's a well-known formula for it:
LCM(A,B) = A * B / GCD(A,B), where GCD(A,B) means the greatest common divisor of A and B, to calculate it we can use a very well-known euclidean algorithm which is described by the pseudo code below, basically it make use of the mathematical formula GCD(A,B) = GCD(A-B,B)

gcd(a,b):
    if b==0 then return a
    otherwise return gcd(b,a mod b)

SETTER'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Can be found here.


team invites

$
0
0

HOW CAN I CREATE A TEAM WITH MY FRIENDS??

SIGSEGV RUN TIME ERROR

October long challenge 2017

$
0
0

Q1.A Balanced contest. 2 cakewalk problems and 3 hard problems can sum up to become a balanced contest. Also test case 2nd explanation is incomplete

Your College Is At Which Position In Codechef Contests?

$
0
0

I think that there sholuld be a ranklist which can also show the rankings of colleges on the basis of contests.This Will also develop a coding culture in their respective colleges.

C00K0FF - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

Author:Hanlin Ren
Tester:Jakub Safin
Editorialist:Jakub Safin

DIFFICULTY

CAKEWALK

PREREQUISITIES

none

PROBLEM

Determine if it's possible to select 5 problems with required difficulties for a Cook-Off, given a list of $N$ problems with known difficulties.

QUICK EXPLANATION

Straightforward - check the given conditions.

EXPLANATION

As the easiest problem in this contest, there isn't much to be said about its solution.

Notice that there are no overlaps among the difficulties required for the 5 problems, so we can just independently check for each problem if at least one of the required difficulties for it appears among the input strings.

We don't even need to remember all the input strings - it's enough to remember how many times each of them appeared in the input. That makes checking the required conditions even easier.

Time complexity: $O(N)$. Memory complexity: $O(1)$.

CHALLENGE

Too easy? You can think about how this problem could be generalised. An arbitrary number of difficulties, arbitrary lists of allowed difficulties for each spot, upper or lower bounds on the total number of used problems of each difficulty, etc...

AUTHOR'S AND TESTER'S SOLUTIONS

Setter's solution
Tester's solution

DP on Trees - Lecture Series | Tutorial

Codechef Rating Predictor

$
0
0

Hello everyone!

alt text

Codechef Rating Predictor

The delay in previous month rating changes + inspiration from CF Predictor and for the practice of a web-application, i tried to write a script that can predict rating changes from ongoing live contests @ Codechef.

While the actual delays in rating changes s/would be fixed, this script can help in predicting rating changes as new submissions are made, so hopefully it can be useful for Long contests :).

The script is written in nodejs and is based on open rating formulas available at this link. The code for the project can be accessed here

Website is currently hosted on Openshift free servers and has few restrictions on use. Therefore the server might be slow or not responding during the period rating changes are calculated. Currently, ratings are expected to be updated every 15 minutes

I also tested rating changes on few past contests and the predictions were accurate within an error of 2 for almost everyone except the first rank (I have no idea why first rank predictions are wrong in some contests using current formulas)

Please note that project is still in beta stage and also actual changes might differ more due to changes in ranklist after plagiarism detection

Your feedback/suggestions would be appreciated

JUNE17 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/all/

Long: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/long/

Few stats on JUNE17 Predictions. I matched ratings (All) of first 6391 users and the results were as follows:

Difference - No of users

  • 0 - 5868
  • 1 - 275
  • 2 - 125
  • 3 - 68
  • >= 4 - 55

There were around 40 users having difference > 50. Turns out some usernames appears to be missing in the ranklist when sorted by rank and hence they were showing as last in the prediction list.

I ran the code again after fixing the above bug and results are better now (Maximum difference is 8)

  • 0 - 5900
  • 1 - 485
  • >= 2 - 6

COOK83 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/all/

Short: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/short/

The ratings are expected to update every 5 minute

Few stats, 4811/4820 predictions (for both all and cook-off predictions) were right. Rest have diff < 3 with the exception of rating prediction of first rank in cook off. Also, as @vikasj554 pointed out, few users got rating changed after initial update. (I still need to figure out why this happened). But even after this 4794/4820 predictions were accurate.

LTIME49 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/all/

Lunchtime : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/ltime/

The ratings are again expected to update every 5 minute

JULY17 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/all/

Long : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/long/

Update frequency: 10 mins


DELISH - Editorial

$
0
0

Problem Link:

Practice
Contest

Difficulty:

Simple

Pre-requisites:

Dynamic Programming

Problem:

Given an array D[1...N], find max(abs((D[i] + ... + D[j]) - (D[k] + ... D[l])) : 1<= i <= j < k <= l <= N).

Explanation:

Let us look at the final solution, and work backwards. Let the final solution be due to some i0, j0, k0, l0. We now have two cases:

Case 1: D[k0] + ... + D[l0] <= D[i0] + ... + D[j0].
In this case, we get that among all possible choices of l, D[k0] + ... + D[l] is MINIMUM for l = l0. Else, we could choose such l, and this would give us a larger absolute difference. We also get, that among all 1 <= i <= j <= k0-1, D[i] + ... + D[j] is MAXIMUM.

Case 2: D[k0] + ... + D[l0] > D[i0 + ... + D[j0].
In this case, among all possible choices of l, we choose l0 to give the MAXIMUM value of the sum, and we choose i0, j0 to give the MINIMUM possible sum.

Hence, it would be useful precomputing values that answer "what is the [minimum|maximum] value I can get if I [start|end] at position i?"

Solution 1

The above setting motivates the following few definitions:
HardLeftMin(i) = Minimum value of the sum of a contiguous subarray whose rightmost point = i.
HardLeftMax(i) = Maximum value of the sum of a contiguous subarray whose rightmost point = i.
SoftLeftMin(i) = Minimum value of the sum of a contiguous subarray whose rightmost point <= i.
SoftLeftMax(i) = Maximum value of the sum of a contiguous subarray whose rightmost point <= i.
HardRightMin(i) = Minimum value of the sum of a contiguous subarray whose leftmost point = i.
HardRightMax(i) = Maximum value of the sum of a contiguous subarray whose rightmost point = i.

Recurrences for the above are easy to find:
HardLeftMin(i) = min(D[i], D[i] + HardLeftMin(i-1)) : either you select position i-1 as well in your subarray and take the best from there, or you don't even take position i-1.
HardLeftMax(i) = max(D[i], D[i] + HardLeftMax(i-1)) : similarly.
HardRightMin(i) = min(D[i], D[i] + HardRightMin(i+1)) : similarly.
HardRightMax(i) = max(D[i], D[i] + HardRightMax(i+1)) : similarly.
SoftLeftMin(i) = min(HardLeftMin(i), SoftLeftMin(i-1)) : either your minimum ends at points i, or it ends at some point <= i-1.
SoftLeftMax(i) = max(HardLeftMax(i), SoftLeftMax(i-1)) : similarly.

Note that, using the above recurrences, we can calculate all the arrays in O(N) time using dynamic programming.

Finally, our case (1) will be covered by SoftLeftMax(j0) - HardRightMin(j0+1), and case (2) will be covered by HardRightMax(j0+1) - SoftLeftMin(j0).
Iterate over all values of j0, and take the maximum, as your answer. This again takes O(N) time to run.

Solution 2

This solution cleverly disposes of SoftLeftMin, SoftLeftMax() functions and works relying on the following claim.

Claim: Without loss of generality, k0 - j0 = 1. That is, we can consider our optimal phases as being consecutive.

Let us say that OPT returned i, j, k, l, with k-j > 1. Now, consider sum S = D[j+1] + D[j+2] + ... + D[k-1]. If S >= 0, then it can be added to the larger of the two segments [i...j], [k...l]. If S <= 0, then the segment can be added to the smaller of the two segments [i...j], [k...l]. In both cases, it gives us a Delish value atleast as good as the Optimal. Hence, wlog, the two segments we choose are consecutive.

Thus, finally, we iterate over j, and consider abs(LeftMax(j) - RightMin(j+1)) and abs(RightMax(j+1) - LeftMin(j)) as candidates. This approach was used by the Setter.

Setter's Solution:

Can be found here

Tester's Solution:

Can be found here

Possible flaw in codechef rating predictor

$
0
0

@vijju123

Today i checked my rating in rating predictor at

https://discuss.codechef.com/questions/100887/codechef-rating-predictor

I found that another user (hh_algos) with rating 2149 and rank 65 is expected to gain 134 points while i, with rating 2141 and rank 58, will gain 94 points.

I'm neither accusing anyone nor blaming, but was interested to know whether the predictor is working correctly or not....

Because a person with better rank and similar ratings ought to gain more.

I have read the codechef ratings page but it didn't helped me much understanding this strange rating prediction

Please helpalt text

Samsung previous question (geeks for geeks)

$
0
0

Only one question with the time limit of 2 hour.Level of problem was moderate. So the Problem statement was: A Research team want to establish a research center in a region where they found some rare-elements.They want to make it closest to all the rare-elements as close as possible so that they can reduce overall cost of research over there.It is given that all the rare-element’s location is connected by roads.It is also given that Research Center can only be build on road.Team decided to assign this task to a coder.If you feel you have that much potential..Here is the Task :- Find the shortest of the longest distance of research center from given locations of rare-elements.

locations are given in the matrix cell form where 1 represents roads and 0 no road.. number of rare-element and their location was also given(number<=5) and order of square matrix was less than equal to (20).

How to solve this?

N Queens problem

$
0
0

Im trying N queens Problem by backtracking. My code doesnt give output a Q in last column . Why So ??

#include <iostream> #include<stdio.h>

#define n 8

using namespace std;
int abs(int x)
{
    if(x<0)
        x=-x;
    return x;
}
bool is_safe(char sol[n][n],int x,int y)
{
    if(x>=0&&n>x&&y>=0&&n>y)
    {
        // check rows
        for(int i=0;i<n;i++)
        {
            if(sol[x][i]=='Q')
                return false;
        }

        //  diagonals checking

        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
           {
              if(abs(i+j)==abs(x+y) || abs(i-j)==abs(x-y))
              {
                  if(sol[i][j]=='Q')
                    return false;
              }

            }
    }

    return true;

}

// Printing Board

 void print_board(char sol[n][n])
 {
     for(int i=0;i<n;i++)
     {
         for(int j=0;j<n;j++)
            printf(" %c ",sol[i][j]);
         printf("\n");
     }
 }
 bool recursive_function(char board[n][n],int column);

bool  solve_N_Queens()
{
    char board[n][n];
    // Initialise

    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
        board[i][j]='*';





    if(recursive_function(board,0)==false)
       {printf("No Solution exists !!!"); return false;}

    else
    { printf("\n\n");
        print_board(board);



return true;}

}

bool recursive_function(char board[n][n],int column)
{
    if(column==n)
        return true;
printf("%d",column);
    int row=0;
    for(row=0;row<n;row++)
    {
        if(is_safe(board,row,column))
        {
            board[row][column]='Q';
              if(recursive_function(board,column+1))
                return true;
                else
                    board[row][column]='*';

        }


    }
    return false;

}



int main()
{
    solve_N_Queens();
    return 0;
}

LECANDY - Editorial

$
0
0

PROBLEM LINKS:

Practice
Contest

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Basic knowledge of arrays and loops.

PROBLEM:

The program asks you to calculate if all the elephants would get the number of candies that they want.

EXPLANATION:

If there are C candies in all, and elephant i needs A[i] candies, then it is possible to serve all the elephants only if there are enough candies available, i.e. the following condition must be satisfied:

C >= A[0] + A[1] + ... + A[N-1]

This means you can have a simple loop over the array A to count the sum of the required number of candies by the elephants and then finally comparing it with C to determine the answer. If the above condition is satisfied, answer will be Yes, else the answer will be No (they have to be case-sensitive to avoid WA).

SETTER'S SOLUTION:

Can be found here.

APPROACH:

The problem setter used the above solution to solve the problem.

TESTER'S SOLUTION:

Can be found here.

APPROACH:

The problem tester used the above solution to solve the problem.

Just One Small Issue

$
0
0

include<bits stdc++.h="">

using namespace std;

int main() { long n1,n2,n3,i,j,count=0,x=0,y=0,z=0,k=0; cin>>n1>>n2>>n3;

 long a[n1],b[n2],c[n3];
 long flag[50000];

 for(i=0;i<n1;i++)
      cin>>a[i];
 for(i=0;i<n2;i++)
      cin>>b[i];
 for(i=0;i<n3;i++)
      cin>>c[i];

 while(x<n1&&y<n2&&z<n3)
 {
      if(a[x]==b[y]&&a[x]==c[z])
      {    //cout<<a[x]<<" "<<x<<" "<<y<<" "<<z<<" 4\n";
           flag[k++]=a[x];
           x++;
           y++;
           z++;
      }
      else if(a[x]==b[y])
      {   // cout<<a[x]<<" "<<x<<" "<<y<<" 1\n";
           flag[k++]=a[x];
                x++;
                y++;
      }
      else if(a[x]==c[z])
      {   // cout<<a[x]<<" "<<x<<" "<<z<<" 2\n";
           flag[k++]=a[x];
           x++;
           z++;
      }
      else if(b[y]==c[z])
      {   // cout<<b[y]<<" "<<y<<" "<<z<<" 3\n";
           flag[k++]=b[y];
           y++;
           z++;
      }
      else if(a[x]>b[y])
           y++;
      else if(a[x]<b[y])
           x++;
      else if(a[x]>c[z])
           z++;
      else if(a[x]<c[z])
           x++;
      else if(c[z]>b[y])
           y++;
      else if(c[z]<b[y])
           z++;
 }
 cout<<k<<"\n";
 for(i=0;i<k;i++)
      cout<<flag[k]<<"\n";

}

//according to me the value of a[x] or b[y] is not getting stored in flag; //Value of k is getting updated

HS08TEST - Editorial

$
0
0

PROBLEM LINK:

Practice

Author:ADMIN

Editorialist:SUSHANT AGARWAL

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Basic looping,Basic Input/Output,Data Types

EXPLANATION:

Please refer to the sample solution given by editorialist.

EDITORIALIST'S SOLUTION:

Editorialist's solution can be found here.


cookoff_code

$
0
0

//what is wrong with the code for cookoff question

include<iostream>

using namespace std; int main() { int T,N; int cakewalk=0,simple=0,medium=0,hard=0,easy=0; cin>>T; while(T!=0) { cin>>N; string a[N]; for(int i=0;i<n;i++) {="" cin="">>a[i]; } for(int i=0;i<n;i++) {="" if(a[i]="="cakewalk")" cakewalk+="1;" else="" if(a[i]="="simple")" simple+="1;" else="" if(a[i]="="easy")" easy+="1;" else="" if((a[i]="="easy-medium")||(a[i]=="medium"))" medium+="1;" else="" if((a[i]="="hard")||(a[i]=="medium-hard"))" hard+="1;" else="" cout<<"wrong="" input";="" }="" if((cakewalk="">=1)&&(simple>=1)&&(easy>=1)&&(hard>=1)&&(medium>=1)) cout<<"yes"<<endl; else cout<<"no"<<endl; T--; } return 0;}

Getting a SIGXFSZ RE.

$
0
0

I'm getting a SIGXFSZ error for the October Challenge question "Chef and a Great Voluntary Program".More specifically for Subtask 2 and Task 2 of Subtask 3.How do i fix this.I am getting ACs for Subtask 1 and Task 1 of Subtask 3.

GDOG - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Pavel Sheftelevich
Tester:Vlad Mosko
Editorialist:Pawel Kacprzak

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Simple math

PROBLEM:

You have $N$ coins. You are about to call any number of people between $1$ and $K$ and divide the coins to them in such a way that each person gets the same amount of coins and this amount is maximal. You take all coins left after this process. Your task is to compute the maximal number of coins which you can get.

QUICK EXPLANATION:

For each possible number of people, compute the amount of coins which are left after the process. Finally, return the maximum from these values.

EXPLANATION:

Let assume that you decided to call exactly $k$ people and you want to divide $N$ coins to them in the way described in the statement. It means, that each person gets the same amount of coins and this amount is maximal from all possible ones. You can simulate this process by giving one coin to all people at once until you have less than k coins, because then you cannot divide them equally. The number of coins which each person has after the process equals $N \mathbin{/} k$, where $\mathbin{/}$ is the integer division, i.e. $7 \mathbin{/} 3 = 2$. Based on this fact, it is easy to see that there are $r = N - k \cdot (N \mathbin{/} k)$ coins left after the process and this is the amount of coins which you get. Here $r$ is called a remainder after dividing $N$ by $k$ and it is very common in computation. Most programming languages have built in operation for computing a reminder. It is often represented by $\texttt{%}$ or $\texttt{mod}$.

Since $K$ is not so big, we can iterate over all possible values of it and for each of them, compute the remainder of $N \mathbin{/} k$, where k is the current number of people, and at the end print the maximum from these remainders.

Time complexity:

We are iterating over K values and for each of them we do constant time operations, so the total complexity is $O(K)$.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

Can anyone help me with this problem??

$
0
0

I am trying to do a coding question, but i am not able to understand it. Here is the question

Q. A cake factory makes various different varieties of cakes. It is the largest factory in the state and takes orders from different places to prepare and deliver cakes. The cake factory has a very large number of employees but not all employees come for work everyday. Due to this, some days the cake factory can make a large delivery while on other days, they may be able to deliver only a handful of cakes.

The factory produces M number of cakes each day and all cakes weigh differently. Every morning, the manager gets an order to deliver N kgs of cake. The factory can either completely deliver the order or not deliver the order at all. Help the manager of the cake factory to determine whether can be delivered for the day or not.

Note: The cakes produced by the factory have to be delivered as a whole; they cannot be cut into pieces.

Constraints 1. 1 <= T <= 1000

  1. 1 <= M <= 1000

  2. 1 <= weight of each cake <= 1000

  3. 1 <= N <= 10000

..Input Format ..First line contains T which indicates the number of days for which the delivery is to be made.

..Second line contains M + 1 space separated integers in which the first integer denotes the number of cakes to be made in one day and the following M integers denote the weight of each cake.

..Third line contains N which indicates the weight of cake in kgs which needs to delivered.

Output Format ..Output YES if the delivery for that day can be made, otherwise NO for each test case.

Sample Input 1
3
4 12 2 15 9

11

7 20 13 5 8 2 11 3

23

3 7 4 1

6

Sample Output 1

YES YES NO

Sample Input 2
2
2 4 7
8

8 2 1 7 6 10 4 2 2

3

Sample Output 2

NO YES

I am not able to get the problem. can somebody please tell me with this.

Competitive Programming Crash Course

$
0
0

I have 4 days[Diwali] holidays coming up this week and want to cover most of the basics topics or questions required such that I can start solving advanced topics like Graph, DP etc. Basically what I am looking for is solving those problems that have some important concepts that will be used repetitively in future like sieve of Eratosthenes. I have basic understanding of programming and am below average in mathematics. So please give me suggestions accordingly.

Viewing all 40121 articles
Browse latest View live


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