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

#include - Compile Time

$
0
0

Is it good to use bits/stdc++.h header file in Codechef or any other competitive platforms? Because according to this link, the first answer says it increases compilation time. In general, I want to know some advantages of using this header, though I know it includes all precompiled headers.


Chef the Brave Warrior Editorial

$
0
0

Problem Link-https://www.codechef.com/problems/EXOCODE5

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

DIFFICULTY:Easy-Medium

PREREQUISITES-Big-Integer,Basic Java Programming

PROBLEM:Chef is a brave Warrior who with his group of young soldiers moves from one place to another to fight against his opponents. Before Fighting he just calculates two things,the difference between his soldier number and the type of opponent’s soldier number.

From this difference and the opponent army soldier number type (even or odd number)?, he decides whether to fight or not?

Print the difference and the type of opponent army soldier number!

Chef ‘s opponent number is never greater than Chef number.

Constraints:The numbers are less than 10^25

EXPLANATION:From the Question statement it is crystal clear that we have to find difference between chef army soldier number and opponent soldier number. Numbers are large so we have to use Big-Integer Class(The java.math.BigInteger class provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java.lang.Math.)

Introduction to Big Integer-https://goo.gl/WZis9f

IN C/C++ -http://codeforces.com/blog/entry/16380

Using BigInteger class function subtract we calculated the difference,then we have to check whether opponent soldier number is even or odd. (A number is said to be even number if it leaves no remainder when divided by 2. There is an alternative definition of even number and it is as a number having any number from 0, 2, 4, 6 and 8 at its ones place is an even number. Examples of even numbers are 12, 66, 456, 9900 and 12342 etc. An odd number leaves a remainder when it is divided by 2. All those numbers having any one from 1, 3, 5, 7 and 9 at their ones places are also called odd numbers.)

So for Checking Whether number is even or odd we can use remainder function,so if number is even we have to print even else print odd

AUTHOR'S AND TESTER'S SOLUTIONS:

import java.util.Scanner;

import java.math.BigInteger;

class ChefBraveWarrior {

public static void main(String []arg)

{
    Scanner in = new Scanner(System.in);

    BigInteger a = new BigInteger(in.next());

    BigInteger b = new BigInteger(in.next());

    BigInteger diff = a.subtract(b);

    if(b.remainder(BigInteger.valueOf(2))==BigInteger.ZERO)
      {
        System.out.println(diff);
        System.out.println("even");
      }
    else
        {
        System.out.println(diff);
        System.out.println("odd");

    }
}

}

edit1-correction

What is offline query?

$
0
0

While trying to solve http://www.spoj.com/problems/DQUERY/en/, I came across an offline solution. It sorted the queries before hand and solved it. Can anyone help me understand the approach? How can storing the queries beforehand solve the problem?

CODEZILLA Hidden Solutions

$
0
0

Why the solutions of CODEZILLA contest are not visible to us @admin? Is it a private contest or there is any BUG in that page?

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?

AC solution in Python for Chef the Brave Warrior.

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?

Kickstart Round A

$
0
0

Hello everyone, There will be a youtube livestream of problem discussion of Round A (Kickstart 2017) by Akashdeep Nain. Also in store is some discussion regarding DS, Algorithms and some tips on how to solve these kind of problems. The link is - https://www.youtube.com/watch?v=WvXbJ8XuGIw It starts at 9:00 PM IST today.

Good luck and Happy learning


Ratings for Institutes In Competetive Programming (CpCtrl.com)

$
0
0

Hello Everyone,

Codechef has been a great platform for motivating and guiding potential competitive programmers on the individual basis. Ratings for all the contests: Long, Short and Lunchtime keep the sense of competition ongoing.

To provide and promote competition on the institution level, I designed a rating list provides unofficial ratings for all institutes ln the basis of Long contests of Codechef. Check it here.

The rating system works on the basis of ELO rating system. For more information about the entire rating system, please check this.

This rating system is entirely unofficial but does motivate the performance on institute level.

Future Additions to the Website:

  • Rating System for Short and Lunchtime challenges.
  • Full Event description regarding total participants and submissions grouped into colleges.

Any more inputs would be most welcomed from all programmers to improve this platform.I hope you all like it.

Edit- Now you can check ratings for cook-off events also.

SSQ - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

DFS, Knapsack

PROBLEM:

We are given a tree, and a set of cost and items associated with each node. We have to compute the optimal spending of 'k' rupees to buy maximum number of items, is we start at the root. and travel each edge exactly once.

QUICK EXPLANATION:

Get all the root to leaf paths using DFS.
On reaching a leaf, use knapsack to calculate the max no. of items in that root to leaf path.

EXPLANATION:

On seeing the question, we notice that it is a tree. So there won't be multiple cycles. Imagine the same question asked for tree whose nodes are connected in a straight line like $1<->2<->3<->.........<->(n-1)<->n$
The problem breaks down to a knapsack. So we convert the given problem into the desired form We can get all the unique root to leaf paths by a single DFS traversal. On reaching a leaf node, we use the knapsack to calculate the maximum acheivable value in that path.

dfs(node, stack, visited):
    visited[node] = true
    stack.push(node)
    leaf = true
    for neighbours of node:
        if visited[neighbour] = false:
            dfs(neighbout, stack, visited)
            leaf = false
    if leaf == true:
        Knapsack(stack)
    stack.pop()

ALTERNATIVE SOLUTION:

Maintain a knapsack at each node and add to it while travelling to children.

GMQ - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

DIFFICULTY:

EASY

PREREQUISITES:

Factorization

PROBLEM:

Given an array, we have to give the sum of factors from L to R

QUICK EXPLANATION:

Store the factorized sum of each element while taking input.
Store the cumulative sum and return $a[r]-a[l-1]$ for each query.

EXPLANATION:

This is a straight away question.
You just need to factorize an element and store all the factors.

for i in (1..n)
    fact[i] = fact[i-1] + factorize(a[i])
for each query
        print fact[r]-fact[l-1]

KSQ - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

DIFFICULTY:

EASY

PREREQUISITES:

Strings

PROBLEM:

We have to check if there exists a string in the given set of strings which can be written by using only the first terms of the set of strings.

QUICK EXPLANATION:

Store all the first letters of the string in an array, and then check each string.

EXPLANATION:

We are given that n,|s| < 100 so we can iterate each string.
We store the first characters of each string while taking the input.
Then we need iterate through all the strings to check if the given string is possible to be written using those first letters.

for i in (1..n):
    cin >> a[i]
    firstLetters[a[i][0]]++
kind=false
for i in (1..n):
    currKind=true
    for each character in a[i]:
        curr[character]++
    for c in ('a'..'z'):
        if(curr[c]>firstLetters[c]):
            currKind=false
    if currKind == true:
        kind = true

Time Complexity: O(n*|s|)

Does CodeChef have any Code Of Conduct?

$
0
0

I am new to CodeChef. I am not sure what can be considered as an improper conduct on this website. I do not want to be penalized for doing something unknowingly which is not the accepted behavior. Is there any such Code of Conduct?

Real meaning of data hiding and encapsulation(Beginners+Expert)

$
0
0

Data hiding and encapsulation, this concepts are never explained in any text beyond the definition and people often misunderstood this concept therefore I have made a video on youTube in which I have explained actual meaning of this concept in detail and how important this concept is. I also make videos on demand, if you find difficulty in understanding anything in java.

LINK TO THE VIDEO

MAKETRI: Getting WA only for 2 cases. Rest AC. What's wrong with my code?

$
0
0

I get WA on Tasks 15 and 16 and AC on the rest. I am not able to spot the bug. Could someone help. Thanks!

Headers included is bits stdc++.h

using namespace std;

long long min(long long a, long long b) {
    if ( a <= b ) {
        return a;
    }
    else {
        return b;
    }
}


long long max(long long a, long long b) {
    if (a >= b ) {
        return a;
    }
    else {
        return b;
    }
}


int main(void) {

    long long n, l, r;

    cin>>n>>l>>r;


    vector<long long> a, left, right;

    long long tmp;
    for (int i = 0; i < n; i++ ) {
        scanf("%lld", &tmp);
        a.push_back(tmp);
    }

    sort(a.begin(), a.end());

    long long le, ri;
    for (int i = 0; i < (n - 1); i++ ) {
        le = a[i+1] - a[i] + 1;
        ri = a[i] + a[i+1] - 1;
        left.push_back(le);
        right.push_back(ri);
    }

    long long res = 0;
    long long endIndex, startValue, currentIndex;
    currentIndex = endIndex = n - 2;
    bool shouldBreakOut = false;


    while ( currentIndex > 0 ) {

        if (right[endIndex] < l) {
            shouldBreakOut = true;
            break;
        }

        startValue = left[endIndex];

        while( ( currentIndex > 0 ) && (startValue <= right[currentIndex-1]) ) {
            currentIndex--;
            if (startValue > left[currentIndex]) {
                startValue = left[currentIndex];
            }
        }


        if (currentIndex > 0) {
            long long rightVal, leftVal;

            rightVal = min(r,right[endIndex]);

            if ( startValue <= l ) {
                shouldBreakOut = true;
                leftVal = l;
            }
            else {
                leftVal = startValue;
            }

            res += (rightVal - leftVal + 1);

            if (shouldBreakOut == true ) {
                break;
            }
            else {
                endIndex = currentIndex - 1;
                currentIndex = endIndex;
            }
        }
    }


    if (n > 2 ) {
        if ( shouldBreakOut == false ) {

            long long leftVal = min(startValue, left[currentIndex]);
            long long rightVal = right[endIndex];

            if ( leftVal <= r && rightVal >= l) {
                leftVal = max(leftVal, l);
                rightVal = min(r, rightVal);
                res += (rightVal - leftVal + 1);
            }
        }
    }
    else {
        long long leftVal = left[0];
        long long rightVal = right[0];

        if ( leftVal <= r && rightVal >= l ) {
            leftVal = max(leftVal, l);
            rightVal = min(rightVal, r);
            res += (rightVal - leftVal + 1);
        }
    }

    printf("%lld\n", res);

    return 0;
}

I think I found a loop hole in MAKETRI February Long Challenge 2017 question's test cases?

$
0
0

Consider the following code, which gets AC with 100 points for the question. The code can be found here:

https://www.codechef.com/viewsolution/13056645

Now, consider the following test case:

3 500 700 1 5 15

The intervals formed by the numbers are [5, 5] and [11,19]. Both these intervals are not present in the [L,R] range of [500,700]. Which implies that the answer for the above test case must be 0.

However, if you were to feed in that test case to the code solution in the link above, it gives 1. Which is wrong.

So, if that test case was included in the original contest, some submissions that got an AC would have got a WA.

Please correct me if I missed out on any constraints, etc and there isn't a loop hole.

How to Use Dynamic Programming in this problem?

$
0
0

Problem-Riya is quite famous for her problem-solving skills in VESIT. When she was facing an interview for placement, a recruiter asked her this question :

Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:

on each path the next number is located on the row below, more precisely either directly below or below and one place to the right. Remember you cannot travel to the number which is below and one place to the left.

Please Explain....

Unethical Karma Farming?

$
0
0

I am finally frustrated and have to post this .I have been observing the codechef profile of this months top contributor @laxman94 for today and have found that most of his upvotes are done by his college mates. Over the past 2 days, his classmates @harryi3t (10 upvotes), @nagendra085 (10 upvotes) and @praveen2jan (6 upvotes) have upvoted almost each and every one of his answers in a bid to increase his karma.This is just todays observation and not for the whole month!

I do not know if he is personally involved in this but i feel it is highly unethical and unfair to people like @kuruma who deserves to be Top Contributor as he has genuinely contributed and is not just getting upvotes from his friends. Please do not indulge in such activities and disturb this wonderful forum otherwise the karma system would completely lost its meaning.

Doubt regading NTT

$
0
0

I have a doubt about how devide polynomial in NTT.Specifically in this problem link :https://www.codechef.com/JULY16/problems/POLYEVAL/ In editorial and many solution,they are deviding polynomial into 3 polynomials. I didn't understand why is needed to devide the polynomial into 3 polynomial first and then apply NTT. Can we take whole polynomial into single array and do it's NTT.Please Clarify my doubt.

ALOST - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

Contributors

Author:Amit Pandey
Tester & Editorialist:Prateek Gupta

DIFFICULTY:

Medium

PREREQUISITES:

Number theory

PROBLEM:

Find any valid array of $N$ integers having $E$ contiguous subarrays with even sum and $O$ contiguous subarrays having odd sum. In case, no such array exists, output "-1" (without quotes).

EXPLANATION


Solution for Subtask 1:
Since, the constraint of $N$ is as small as $15$, it can be easily solved by bit masking. It is a simple realization that each of the $N$ integers will be either odd or of even parity and that is how the count of even sum and odd sum contiguous subarrays will be impacted. Having said that, we can place either an odd or an even integer in each of the $N$ places. This gives rise to iterating over all sets of combinations and finding the valid one if it exists.

         for ( mask = 0 to 2^n - 1 ) {

               a[0] = 0
               even_subarrays = odd_subarrays = 0

               for ( j = 0 to n - 1 ) {
                    if ( bit j is set in mask ) a[j + 1] = 1
                    else a[j + 1] = 0
               }

               for ( j = 1 to n ) {
                    sum = 0
                    for ( k = j to n ) {
                        sum += a[k], sum %= 2
                        if ( sum ) odd_subarrays += 1
                        else even_subarrays += 1
                    }
               }

               if ( even_subarrays == E and odd_subarrays == O ) {
                    print(array, a)
                    exit
               }
         }

         print("-1")

The overall complexity for the above approach is $\mathcal{O}(N^2*2^N)$ which is exponential and hence too slow for the rest of the subtasks.


Solution for subtask 2 & 3:

The key to approach the optimized solution is to start from backwards.
Let us denote the $prefixSum_i$ as the sum of first $i$ integers of any valid array to be computed. Now, there are some important observations.

  • If you somehow know the number of prefixSums having odd and even parity respectively, you can correspondingly create any valid array provided that total count of oddPrefixSums and evenPrefixSums is $N\ +\ 1$. For eg :- If you have 3 evenPrefixSums and 2 oddPrefixSums, you can create an array $[0,\ 0,\ 1,\ 0]$. The trick is to place an only $1$ after placing $evenPrefixSums\ -\ 1$ zeros. All the remaining prefixSums will obviously be of odd parity. Having said this, the following equation holds true.
  • $$evenPrefixSums\ +\ oddPrefixSums\ =\ N\ +\ 1$$
  • How to calculate the number of contiguous subarrays having odd parity? Since, $prefixSum_i\ -\ prefixSum_j$ contributes to sums of contiguous subarrays, both should be of different parity. Hence, number of contiguous subarrays having odd parity will indeed be $C(evenPrefixSums,\ 1)*C(oddPrefixSums,\ 1)$. This gives rise to another equation.
  • $$evenPrefixSums\ *\ oddPrefixSums\ =\ O$$
Now, you have two equations and two unknown variables, therefore you can compute the values for evenPrefixSums and oddPrefixSums which will in turn give you the valid array as discussed.

How to compute the number of evenPrefixSums and oddPrefixSums?

Approach 1
Looking at equation $2$ which is of the form $a*b\ =\ X$, you can go ahead to compute the divisors of $X$ which will satisfy $a\ =\ i$ and $b\ =\ X/i$ provided that $X\ mod\ i\ =\ 0$. If any such pair of $(a,\ b)$ also satisfies the equation $1$ of the form $a\ +\ b\ =\ Y$, we get a valid pair. Find the pseudo code below for the same.

    LIM = square_root(odd)

    for ( i = 1 to LIM ) {
        if ( odd % i == 0 ) {
            if ( i + odd/i == n + 1 ) {
                odd_prefix_sums = i
                even_prefix_sums = odd/i
            }
        }
    }

Approach 2
Alternatively, you can form a quadratic equation and solve it to get the respective values. If you do not find any valid values, output "-1".

Note
Depending upon your implementation, cases having $E$ or $O$ as $0$ might be tricky.

For more details on the implementation of any subtasks, have a look at the tester's solution. If you want to enjoy a good reading about other Number theory algorithms, feel free to visit this blog post.

COMPLEXITY

Overall time complexity for the above approach is $\mathcal{O}(N)$ per each test case.

SOLUTIONS

Setter
Tester's solution to Subtask 1
Tester's solution to Subtask 2 & 3 - Approach 1
Tester's solution to Subtask 2 & 3 - Approach 2

Viewing all 40121 articles
Browse latest View live


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