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

Video Editorial - FEB17 - GERMANDE


What are karma points?

$
0
0

I am new to this karma system, Can you explain me why is it called so? What has karma points got to do with contribution?

Unofficial editorial of first five questions (not SORTROW) of MAR17 Long contest.

$
0
0

Hello guys,

I have a Facebook page where I try to post my approach to the problems I solve in any contests. I created this page for two reasons, First, to revise any new things I may have learnt during the contest and second, to help any new users/medium users to learn new things. I try to answer to as many doubts as possible. If you think, the page would help you feel free to like and follow the page. "https://www.facebook.com/algo0111/posts/200339503784614".

Thanks.

feb. long challenge 2017

$
0
0

Just saw video tutorial and tried to implement MFREQ question... can anyone tell me what am I missing at? here is my code:

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

using namespace std;

int main() {

int n,m;
cin>>n>>m;
long long a[n],left[n],right[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<m;i++){
    int l,r,k;
    cin>>l>>r>>k;

    left[0]=0;
    for(int i=1;i<n;i++)
    {
        if(a[i]==a[i-1])
        left[i]=i-1;
        else
        left[i]=i;
    }
    right[n-1]=n-1;
    for(int i=n-2;i>=0;i--)
    {
        if(a[i]==a[i+1])
        right[i]=i+1;
        else
        right[i]=i;
    }
    for(int i=0;i<n;i++)
    cout<<left[i]<<" ";    //left array
    cout<<endl;
     for(int i=0;i<n;i++)
    cout<<right[i]<<" ";   //right array
    int  mid=(l+r)/2;

   if((right[mid]-left[mid])>=k)    // not getting this condition
    cout<<a[mid]<<endl;
   else
   cout<<-1<<endl;
}

}

Please help me...

CODEZILLA question

PSHTBRTH - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Ivan Fekete
Testers:Sergey Kulik, Kamil Dębowski
Editorialist:Pawel Kacprzak

DIFFICULTY:

Medium

PREREQUISITES:

Game theory, Sprague–Grundy theorem, Segment tree

PROBLEM:

Two players play a game with $N$ binary matrices of size $4 \times 4$ arranged in a row and numbered from $1$ to $N$. They play optimally and make moves in turns. In one move, the current player can select any non-zero matrix, then select any its submatrix containing only $1$'s and replace all of these $1$'s with $0$'s. The player who cannot make a move is declared the loser and the other player is declared the winner. The goal of the problem is to handle $M$ queries. Each query either changes one of the matrices or asks who is the winner if the game is played on the matrices in a range $[L, R]$.

QUICK EXPLANATION:

Use Sprague-Grundy theorem to decompose the game into separated games, each played with a single matrix. Then, for each of $2^{16}$ possible matrices compute the Grundy value of a single game played with that matrix. Finally, handle the queries with a segment tree using the fact that the Grundy value of a game played on matrices in a range $[L, R]$ is a XOR of Grundy values of games played with single matrices in that range.

EXPLANATION:

Subtask 1

In the first subtask, both $N$ and $M$ are at most $10$, so the constraints are quite low. This allows, for example, a solution similar to the one used for the third subtask, but with computing the Grundy values using a plain recursion with any memoization or dynamic programming.

Subtask 2

In the second subtask, we have $N, M \leq 1000$. The solution for these constraints is a slow implementation of the solution for the third subtask. For example, one can use a linear scan in order to handle each of $M$ queries in $O(N)$. Please refer to the next section for more details.

Subtask 3

In this subtask, we have $N, M \leq 10^5$. The intended solution is to use Sprague-Grundy theorem to decompose the game on matrices in a range $[L, R]$ into $R-L+1$ games played with a single matrix, solve each of these games fast, and then compute the winner of the original game using the theorem and results of these smaller games.

Let's consider a game played on a single matrix. We are going to assign every position in such a game a Grundy value, also denoted as mex. The idea is that a terminal position gets value $0$. In our case, the zero matrix, i.e. the matrix containing only zeros, is the terminal position of the game, so it gets value $0$. Then, let's consider any non-zero matrix $A$. Let also $P$ be a set of matrices reachable from $A$ in a single move (remember that in a single move the current player selects a submatrix of $A$ containing all $1's$ and changes all these $1's$ to $0$'s). Then, the Grundy value of matrix $A$ is defined as the smallest non-negative integer which is not a Grundy value of any matrix in $P$. For example, if $A$ have only one cell with value $1$, then $P$ contains only the zero matrix, so the Grundy value of $A$ is $1$ because the Grundy value of zero matrix is $0$. Notice that we can use memoization or dynamic programming in order to compute these Grundy values fast and avoid solving multiple subproblems many times.

Moreover, the position of a game with Grundy value $G$ is a winning position if and only if $G \neq 0$.

There are $2^{16}$ possible matrices to consider, and we are going to compute Grundy values for all of them. For a fixed matrix $A$, this can be done by computing the set $P$ of matrices reachable from $A$ in a single move, computing their Grundy values recursively and then assigning the smallest non-negative integer not present in the set of Grundy values of matrices in $P$ as the Grundy value for $A$. For implementation details please refer to multiple solutions attached below.

Now, we have computed a Grundy value for every possible game played with a single matrix and the next step is to use the Sprague-Grundy theorem in order to get the value of a game played with matrices in a range $[L, R]$. The theorem states that the Grundy value of a game being a composition of $K$ games is the XOR of Grundy values of these games. Thus, if we want to compute the Grundy value of a game played on matrices in a range $[L, R]$, we just XOR Grundy values of games on a single matrix played with matrices in that range. It follows that the first player has a winning position if and only if the Grundy value of the game played with matrices in a range $[L, R]$ is non-zero.

Finally, to handle all the $M$ queries fast enough, we can use a segment tree or a Fenwick tree, in order to support both computing XOR of a range of values and updating a single value in that range. Segment tree supports these operations in $O(\log N)$ time, so after the precomputation of Grundy values is done, the complexity of handling all the queries is $O(M \cdot \log N)$. For implementation details please refer to multiple solutions liked below.

AUTHOR'S AND TESTER'S SOLUTIONS:


Setter's solution can be found here.
First tester's solution can be found here.
Second tester's solution can be found here.
Editorialist's solution can be found here.

SPOJ - Problem AGGRCOW - Aggressive cows

$
0
0

I cannot understand how binary search will solve the problem.

Problem statement is here

Need Help! Thanks :)

Chef and Array-Editorial

$
0
0

PROBLEM LINK-https://www.codechef.com/problems/EXPCODE1

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:EASY

PREREQUISITES:Array,Sorting

PROBLEM:Being a programmer, Chef like arrays lot. On Chef' birthday,Chef friends given him an array "a" consists of n distinct integers. Unfortunately, the size of array "a" is too small. Chef want a bigger array!,Chef friends agree to give him an bigger array. but only if Chef is able to answer the following questions correctly: 1-Largest element in array a 2-Kth largest element Help him for getting bigger Array!

EXPLANATION:First We need Largest Element in the Array,so we have to Sort the Array,you can use any sorting technique(bubble sort,quick sort,etc) because there is no issue of Constraints and then print the largest element in array a[ n-1 ],Then answer for 2nd Question is print a[n-k],because we know the kth largest element is at position n-k

Algorithm:

begin BubbleSort(list)

for all elements of list

  if list[i] greater list[i+1]
     swap(list[i], list[i+1])
  end if
  end for

return list
end BubbleSort

Implementation: https://goo.gl/oKM4kb

AUTHOR'S AND TESTER'S SOLUTIONS:http://campus.codechef.com/EXCO17TS/viewsolution/13037182/

Edit1-Link+Corrections


LEDIV - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

DIFFICULTY

SIMPLE

PREREQUISITES

Simple Math

PROBLEM

You are given a list of numbers. You have to find the smalelst number which divides all these numbers.

QUICK EXPLANATION

To the initiated, this question should be a breeze.

  • Find the GCD of the list of numbers.
  • Find the smallest prime factor of the GCD.

EXPLANATION

The GCD of two numbers can be found using the Euclid's Algorithm.

gcd(a,b)
    return (b == 0) ?
        a : gcd(b, (a mod b))

The GCD of a list of numbers A[1 ... N] can be found as

let G = 0

for i = 1 to N G = gcd( A[i], G )

The above is intuitive and easy to prove by induction.

Now, the next step is to find the smallest prime factor of the GCD. Calculating this can be done in O(sqrt(N)) time easily.

for i = 2 to floor(sqrt(G))
    if G is divisible by i
        return i
return G  // Since G is prime!

This calculation is probably the most time consuming step in the solution. Although, iterating till sqrt(G) will fit within the time limit, you can make one optimization to make it faster. That optimization is pre-calculation! You can pre-calculate the smallest primes in the factorization of any number by sieving.

Consider the snippet below

smallestPrime[ 2 ... N ] // We will store our answers here
for i = 2 to N
    smallestPrime[i] = i
for i = 2 to N
    if smallestPrime[i] = i
        for j = 2*i to N, step-size i
            smallestPrime[j] = min( smallestPrime[j], i )

Notice how we modify the step in which in the usual Sieve of Eratosthenes, we set the multiples of i as non-prime. In this step now, we are simply updating the smallestPrime array at index j. This is a very clever trick to master while solving problems. When you deal with a problem where you need to perform an operation based on all prime factors of a number (like in this case, we wanted to find the smallest of them), a small code snippet like above is usually needed.

SETTERS SOLUTION

Can be found here.

TESTERS SOLUTION

Can be found here.

Can someone please provide me with Editorial of Problem BASE (December Long Challenge 2016)

Chef and Ola Cab-Editorial

$
0
0

PROBLEM LINK:https://www.codechef.com/problems/EXPCODE2

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:EASY

PREREQUISITES:Basic Maths,Math Functions

PROBLEM: Chef want to book Ola Cab,he have to take ride from point one (xi,yi) to second point (xj,yj),Ola cost N rupees per unit, Chef have R rupees in his pocket, You have to help Chef to find Whether he have suffiecient amount of money in his pocket for paying to ola.

if yes print “yes”(without quotes) else print “no”(without quotes)

EXPLANATION: From the Question,its clear we have to find distance between two points.

Distance Formula: Given the two points (x1, y1) and (x2, y2), the distance d between these points is given by the:alt text

find the distance d between 2 points then we know ola cost N rupees per unit so,

total cost=d(distance) * N(Cost of Per Unit).

so if total cost<=R(Amount chef have in his pocket) then Print yes else print no

AUTHOR'S AND TESTER'S SOLUTIONS:

class chefandolacab {

public static void main(String[] args)

{

    Scanner sc=new Scanner(System.in);

    int x1=sc.nextInt();

    int y1=sc.nextInt();

    int x2=sc.nextInt();

    int y2=sc.nextInt();

    int r=sc.nextInt();

    int n=sc.nextInt();

    double dist=Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));

    if(dist*r<=n)
    System.out.println("yes");

    else
        System.out.println("no");

}

}

Edit-Correction :)

StopStalk: Tool to maintain your algorithmic progress

$
0
0

Hello Coders,

Hope you are having a great time coding hard. Here I present to you a Utility tool - StopStalk which will encourage you to keep your algorithmic progress going by coding with your friends and improve.

It retrieves your friends’ recent submissions from various competitive websites(CodeChef, Codeforces, Spoj, HackerEarth and HackerRank for now) and shows you in one place. It includes lots of other features like - User streak notification, Global Leaderboard, Filter submissions, search problems by tags, and a lot more… You can send friend requests to your friends on StopStalk or you can also add a Custom User. Register here - StopStalk

The goal is to involve more and more people to Algorithmic Programming and maintain their streak. Also the project is completely Open Source - Github

Feel free to contribute. :)

We would be happy to hear from you - bugs, enhancements, feature-requests, appreciation, etc. In the end - Stop Stalking and start StopStalking! Happy coding!

PS: We update our database every 24 hrs but just for today we will update it every 3 hrs. So don’t miss this opportunity to register.

Easy One-Electricity Bill Editorial

$
0
0

Problem Link:https://www.codechef.com/problems/EXOCODE7/

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:Cakewalk

PREREQUISITES:basic programming,basic maths

PROBLEM:Chef wants to calculate his Electricity bill,Help him to do so

Acc to Conditions:-

For First 50 units Rs 0.50/unit

For next 100 units Rs 0.75/unit

For next 100 units Rs 1.20/unit

For unit above 250 Rs 1.50/unit

An additional surcharge of 20% is added to the bill

EXPLANATION: Below is the step by step descriptive logic to compute electricity bill.

1-Read units consumed by the customer in some variable say unit.

2-If user consumed less or equal to 50 units. Then amt = unit * 0.50.

3-If user consumed more than 50 units but less than 100 units. Then add the first 50 units amount i.e. 25 to the final amount and compute the rest 50 units amount. Which is given by amt = 25 + (unit-50) * 0.75. I have used units-50, since I already calculated first 50 units which is 25.

4-Likewise check rest of the conditions and calculate total amount.

5-After calculating total amount. Calculate the surcharge amount i.e. sur_charge = total_amt * 0.20. Add the surcharge amount to net amount. Which is given by net_amt = total_amt + sur_charge.

AUTHOR'S AND TESTER'S SOLUTIONS:

include <stdio>

int main()

{

int unit;

float amt, total_amt, sur_charge;

/*
 * Read unit consumed from user
 */
printf("Enter total units consumed: ");
scanf("%d", &unit);


/*
 * Calculate electricity bill according to given conditions
 */

if(unit less then equal to 50)
{
    amt = unit * 0.50;
}
else if(unit less then equal to 150)
{
    amt = 25 + ((unit-50)*0.75);
}
else if(unit less then equal to 250)
{
    amt = 100 + ((unit-150)*1.20);
}
else
{
    amt = 220 + ((unit-250)*1.50);
}

/*
 * Calculate total electricity bill
 * after adding surcharge
 */
sur_charge = amt * 0.20;
total_amt  = amt + sur_charge;

printf("%.2f", total_amt);

return 0;

}

Note-->printf("%.2f) is use for controlling precission

ALEXNUMB - Editorial

$
0
0

Problem: You are given an array of N numbers. You are to find the number of pairs of numbers in the array s.t a[i] < a[j].

Solution: First you find the set of all distinct elements in the array {x(1), ..., x(M)} with x(i) < x(i+1) and their corresponding counts {c(1),...,c(M). Now it is easy to see that the required number of such pairs is Sum_{i} (c(i) * (c(1)+..c(i-1)) This is simply Sum_{i} (c(i) * c_cumulative(i-1)) where c_cumulative(k) is the cumulative sum of c() that can be computed in O(M) time. Thus, the total counts of such pairs can be computed in O(N).

Chef and Palindrome Editorial

$
0
0

Problem Link:https://www.codechef.com/problems/EXOCODE3

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:Medium

PREREQUISITES:Algorithms,Hashing,Array,String

PROBLEM:Chef like palindrome strings more than normal trings ,so chef Just want to check if characters of a given string can be rearranged to form a palindrome string or not.

Help him to check, print YES if its possible,else print NO

EXPLANATION:

Palindrome String:A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome

A set of characters can form a palindrome if at most one character occurs odd number of times and all characters occur even number of times.

A simple solution is to run two loops, the outer loop picks all characters one by one, the inner loop counts number of occurrences of the picked character. We keep track of odd counts. Time complexity of this solution is O(n^2),This will lead to tle(Time Limit Exceeded)

We can do it in O(n) time using a hash array. Following are detailed steps.

1) Create a hash array,which is typically of size 26 because string "s" will contains only lowercase alphabets. Initialize all values of count array as 0.

2) Traverse the given string and increment count of every character.

3) Traverse the hash array if the hash array has less than or equal to one odd value then answer is YES else NO

AUTHOR'S AND TESTER'S SOLUTIONS:

import java.util.Scanner;

class chefandpalindrome

{

public static void main(String[] args)

{

    Scanner sc=new Scanner(System.in);

    String s=sc.next();

    int hash[]=new int[26];

    for(int i=0;i<s.length();i++)
    {

       hash[s.charAt(i)-97]++;  //hashing is done here

    }

    int cnt=0;

    for(int i=0;i<26;i++)
    {

       if(hash[i]%2!=0 && hash[i]!=0) //check the hash array
           cnt++;

    }


    if(cnt<=1)
        System.out.println("YES");
    else
        System.out.println("NO");
        }

}


Chef and Array Update Editorial

$
0
0

Problem Link:https://www.codechef.com/problems/EXOCODE4

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:CakeWalk

PREREQUISITES:Basic Programming,Array

PROBLEM:Chef Purchased an array A having N Integer values,After Playing it for while,he got bored of it and decided to update value of its element.In one second he can increase value of each array element by 1.He wants each array element’s value to become greater than or equal to K.

Please Help Chef to find out the minimum amount of time it will take,for him to do so..

EXPLANATION:Since we can only increase all the elements by 1, the minimum element will take most step to reach K.So we have to find the minimum element in array A and answer will difference between K and minimum element.

One corner case is if K is less than minimum element in the array A

Time Complexity:O(N)

AUTHOR'S AND TESTER'S SOLUTIONS:

alt text

Note: We can also use Sorting(Bubble,Quick,etc) to find minimum element in Array, but this will increase time complexity

Red, Green or Yellow colors not given to the problems in contests.

$
0
0

Earlier Red, Green or Yellow colors were given to the problems in the contests describing whether we didn't solve them, we solved them or we solved them partially. That feature was very good but why was it removed? Can we have that feature again?

Doubt in Time complexity

$
0
0

There is a question Chef and Numbers. According to Editorial it is purely based on FFT having overall time complexity $O(n * log(n))$. But after crawling other solution i found one of the solution which is Based on Dynamic programming. So the doubt is about it's time complexity which seems to be $O(n^2)$.

Can anyone tell me the full explanation about it's real complexity of that ACsolution?

Chef and Weird Spider Editorial

$
0
0

Problem Link:https://www.codechef.com/EXCO2017/problems/EXOCODE6

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:Easy

PREREQUISITES:Conditional statements and loops,Basic Programming

PROBLEM:Chef School of Witchcraft and Wizardry is known for moulding young minds into the finest wizards and witches. However that comes with a lot of practice. One of the young wizards cast a spell on a spider that makes it leap greater distances.

On observing closely the spider leaped 1 meter in its first leap. 10 meters in its second leap, 19 meters in its third leap , 28 meters in its fourth leap, 37 meters in its fifth leap and so on following a pattern.

In order to capture the spider, the young wizard must be able to tell the number of leaps the spider would take to reach a given distance.

EXPLANATION:It is clear that leap length is increased by 9 in every leap,So Now we have to count the minimum number of leaps required to a cover a distance >=N,so we count minimum no of leaps by using while(true) loop because we dont know the number of iterations exactly required to find minimum no of leaps.

Output must be in format: Case #1: (answer)

AUTHOR'S AND TESTER'S SOLUTIONS:

include<iostream>

alt text

Regarding MARCH17 SCHEDULE

$
0
0

Hello, I just submitted a relatively naive solution to the SCHEDULE problem of MARCH17. It was accepted for 100 points. I think that the test cases for this problem are weak. Could the problem setters please look into it?

Viewing all 39796 articles
Browse latest View live


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