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

IPCTRAIN - Getting WA for higher data sets.

$
0
0

I tried many times this question but getting WA for higher test cases. Since i did it with by two ways.

(1) Firstly i create a priority queue using STL(which is max heap by default) and then start loop for days 1 to D, and at the beginning of each i'th day, I put all the members who are coming on i'th day into queue and if queue is empty(in case of no trainers are available for those days) then do nothing. but if queue is not empty then then pop from queue and decrease its demand by 1 and if demand is still not zero then push it again into queue. and at last(after camp gets completed) all the elements that left in queue will give the answer I tried it many times but getting AC only for small data sets. You can check my solution here

(2) After getting too many WA i did it using heap(std stl heap<algorithm>) with same approach as above. But only time running time gets reduced, as still getting WA for higher data sets. You can see my second solution here.

Now Please tell me what's wrong in my code.. Thanks in advance.


Cheating : July long 2017

$
0
0

Hello Community!
I found a YouTube channel which posted videos of solutions of many of the July Long Challenge problems! Here is a link to one of the video I found : link.
I found the video when the challenge was live but did not post it since it would encourage more copying! Some strict action should be taken against such channels and I request @admin to take some steps as this types of things ruin the leaderboard!
Hope we have fair long challenges soon!
Thanks :)

Run time error NZEC.

$
0
0

/ package codechef; // don't place package name! /

import java.util.*;

class coins
{

    public static void main (String[] args)
    {

    Scanner in = new Scanner(System.in);
    int test;
    int numOfGames;
    int initial;
    int rounds;
    int target;
    //System.out.println("Enter the number of test cases:");
    test = in.nextInt();

        while (test-- != 0){
        //System.out.println("Enter the number of games:");
        numOfGames = in.nextInt();
        while (numOfGames-- != 0){
            //System.out.println("Enter initial, rounds and target:");

            initial = in.nextInt();
            rounds = in.nextInt();
            target = in.nextInt();

            int[] coins = new int[rounds];
            for (int i=0; i<rounds; i++){
                coins[i] = initial;
            }
            for (int i=0; i<rounds; i++){
                for (int j=0; j<=i; j++){
                    if (coins[j] == 1)
                        coins[j] = 2;
                    else
                        coins[j] = 1;
                }
            }
            int count = 0;
            for (int i=0; i<rounds; i++){
                if(coins[i] == target)
                    count += 1;
            }
            System.out.println(count);
        }
    }

}

}

Its showing runtime error NZEC. Can someone please check my code? i'm new to codechef.

NITIKA - editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Abhinav Jain
Primary Tester:Misha Chorniy
Editorialist:Hussain Kara Fallah

DIFFICULTY:

Cakewalk

PREREQUISITES:

None

PROBLEM:

Given names of people. Each name may consist of at least one and at most three parts. You are asked to show the name with replacing the first two parts (if they exist) with the first letter of each (abbreviation) and followed by the last part (last name). Abbreviations should be upper case letters. Only the first letter of the last name should be in uppercase.

EXPLANATION:

This problem is straight forward implementation (string manipulation). Each name will be given on a separate line, so we should read each line completely (one by one). We have to find the parts of each name and separate them from each other. Since each two consecutive parts are separated by a space,we should be looking for spaces in each line. The first space (if it exists) separates between the 1st and the 2nd part, the second space (if it exists) separates between the 2nd and the 3rd part. Finding spaces on each line would make us able to break our full name into parts (This can be done manually by a loop).

My solution uses stringstream (C++ class) which is very useful for parsing input and solves this problem easily. A brief explanation can be found here :stringstream

After breaking the name into parts we should capitalize the first letter of each part. We should output only the first letter of each part capitalized (except the last part). As for the last part, we must set its first letter to uppercase, and the rest of its letters to lowercase. After that, we can print it.

AUTHOR'S AND TESTER'S SOLUTIONS:

AUTHOR's solution: Will be found here
TESTER's solution: Will be found here
EDITORIALIST's solution: Will be found here

Doubt - SRVRS July 17

$
0
0

Can anyone tell where has my code gone wrong ?(CODE)
it shows -1.00 as execution time as well.

Merge Sort Tree - Tutorial

$
0
0

Prerequisites : Segment Trees

Target Problem : Given an array of N elements and you have to answer Q queries of the form L R K , To Count the numbers smaller than K in range L to R.

Key Idea : The key idea is to build a Segment Tree with a vector at every node and the vector contains all the elements of the subrange in a sorted order . And if you observe this segment tree structure this is some what similar to the tree formed during the merge sort algorithm ( Yes , thats why they are called Merge Sort Trees ) .

Building the tree :

vector<int>tree[5*N];
int A[N];
Void build_tree( int cur , int l , int r )
{
     if( l==r )
     {
            tree[cur].push_back( a[ l ] );
            return ;
     }
     int mid = l+(r-l)/2;
     build_tree(2*cur+1 , l , mid ); // Build left tree
     build_tree(2*cur+2 , mid+1 , r ); // Build right tree
     tree[cur] = merge( tree[2*cur+1] , tree[2*cur+2] ); //Merging the two sorted arrays
}

Querying the tree :

int query( int cur, int l, int r, int x, int y, int k)
{
       if( r < x || l > y )
      {
               return 0; //out of range
      }
      if( x<=l && r<=y )
      {
              //Binary search over the current sorted vector to find elements smaller than K

              Return upper_bound(tree[cur].begin(),tree[cur].end(),K)-tree[cur].begin();
      }
      int mid=l+(r-l)/2;
     return query(2*cur+1,l,mid,x,y,k)+query(2*cur+2,mid+1,r,x,y,k);
}

Build function Analysis : Build a merge sort tree takes O(NlogN) time which is same as Merge Sort Algorithm . It will take O(NlogN) memory because each number Ai will be present in at most LogN vectors (Height of the tree ) .

Query function Analysis : A range L to R can divided into at most Log(N) parts, where we will perform binary search on each part . So this gives us complexity of O(LogN * LogN) per query .

Handling Point Updates : The only reason that we cant handle updates on MST in this code is because its merge function takes too much time, so even if theres a point update it will lead to O(N). So the major issue is of vectors and rearranging them on updations, but why do we need vectors ? Just to find the elements smaller than K in that complete vector, right ? Lets forget about vectors and keep policy based data structure at each node which handles three queries (insertion , deletion and elements smaller than K in the set) in O(LogN) time . So now no need to rearrange vectors and we can use insertion - deletion to handle point queries . This is just an idea , we can discuss this in comments again if anyone has a doubt .

Bonus : How to use this to solve the query of type Kth smallest number in range L to R ? So we can binary search over the solution and find the value which has exactly K numbers smaller than it in the given range . Complexity : O(LogN * LogN * LogAi ) per query .

Why to use MST: Apart from the code simplicity, they answer queries online . We could have used some offline algorithms like MOs or even Segment tree but come on, Online Querying is great because it can be used in Dp Optimisations and stuff like that . Peace Out .

problems needed

$
0
0

Can someone suggest some problems(can be from anywhere) where I need to deal with lots of corner cases.. Thanks in advance. :)

What kind of comment should I post on the problem page?

$
0
0

Is there any comment posting guideline? I am new on this website. I have so many doubts while I participate in a contest. Can I ask them on the problem page by posting a comment? Will I be banned for asking something which is not relevant?


Code is Successfully Executed, but on Submission shows Wrong Answer.

$
0
0

Need Help!! my code is successfully executed in Code,Compile & Run Panel of Codechef but on submission shows Wrong answer. The Question Code is ENTEXAM(Entrance Exam) of Begineer level.And, my code is:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int t;
    cin>>t;
    while(t>0)
    {
        int n,k,p,m,i,j;
        long long int sum,temp;
        cin>>n>>k>>p>>m;
        long long int total[n-1];
        for(i=0;i<n-1;++i)
        {
            sum=0;
            for(j=0;j<p;++j)
            {
                cin>>temp;
                sum+=temp;
            }
        total[i]=sum;
        }
        sum=0;
        for(i=0;i<p-1;++i)
        {
            cin>>temp;
            sum+=temp;
        }
        sort(total,total+(n-1));
        if ((k>n)||(sum>total[n-k-1]))
        cout<<"\n";
        else
        {
            if((total[n-k-1]+1)-sum<=m)
            cout<<(total[n-k-1]+1)-sum;
            else
            cout<<"Impossible";
        }
        t--;
    }
    return 0;
}

Nuclear reactors easy Section problem

Persistence Made Simple - Tutorial

$
0
0

This assumes you already have a basic knowledge of segment trees.For this discussion, I want to show everyone that persistence can actually be made simple just by changing our way of thinking.

Money Grows on the Tree of Persistence

Introduction

Usually, persistence is treated as a "really hard" kind of data structure. After all, it's like a dream data structure with robust version control. It's the crowd favorite for long challenges because of its fame to as the "hardest to implement", especially when appended with truly hard concepts in other topics. In reality, persistence can actually be made simple, as it is literally only one step away from the non-persistent version.

Background

Why does the idea of a persistent data structure seem so hard for most programmers? I think this is because most of us started with imperative programming languages like C++, Java, and Python, where changing values of variables is the norm. We are familiar with having the power to mutate a value anytime we want. In contrast, most of us cringe whenever we deal with immutables. Hail C++ mutable std::string, screw Java's immutable String. Nothing beats plain simple assignment operator (s[i] = c) compared to the read-only (s.charAt(i)). Most, if not all of us, grew with the mutable mindset. We live and breathe mutability in our code. It is our intuitive art.

Immutable Programming

But when you think about it, persistence is all about staying immutable. Being persistent means we discard our powers of mutability. Just like how Java's String class is immutable, we avoid changing individual values directly. Though at first this seems dumb and inefficient, when you think about it it's the straightforward way to do version control. Since original content stays the same, having a new version of the content won't damage the version of the original. For immutables, the way to "change" is to "create". The truth is persistence == immutability, hence we can summarize the act of staying persistent with one golden rule.


GOLDEN RULE OF PERSISTENCE

Create new nodes instead of changing them.


That's it? Yes, that's it! The way to be persistent is to stop using the assignment operator, and instead focus on recreation of nodes during a change. We return new nodes instead of mutating. That's the only additional step we need to transform from mutable to persistent. In REMOVING our capability to be mutable, we force ourselves to CREATE a new way to do version control. In effect, original content can stay the same.

The secret is that there is no secret

Persistence is actually straightforward. There's no need to fancy things around. Just replace all assignment operators with a new node() expression or similar. It is no exaggeration to say that it is a mere few lines of code away from the mutable version. The "god data structure" everyone thinks is so complicated is in truth something with removed powers than the original. But with this irony of a removed power, we instead gain a new power called efficient version control.

IMPLEMENTATION

Let's demonstrate an example of adding persistence to a segment tree. Suppose we want to solve the range sum query problem, but with a persistent data structure. We could implement it the usual segment tree way as follows:

Build (usual segment tree)

#define M ((L+R)/2)
int st[4*n];
void build(int arr[], int p=1, int L=0, int R=n-1) {
    if (L == R) st[p] = arr[L]; // construct as leaf
    else { // construct as parent
        build(arr, 2*p, L, M);
        build(arr, 2*p+1, M+1, R);
        st[p] = st[2*p] + st[2*p+1];
    }
}

Now how do we make this persistent? What we do is that we replace every assignment operator st[p] = ... with a new() operator. See my example below for the details.

Build (persistent segment tree)

#define M ((L+R)/2)
int build(int arr[], int L=0, int R=n-1) {
    if (L == R) return newleaf(arr[L]); // construct as leaf
    else return newparent(build(arr, L, M), build(arr, M+1, R)); // construct as parent
}

// Usage: int root = build(arr, 0, n - 1);

We abstract the idea of "change" via "creation", as per the golden rule of persistence. Isn't it really simple? In fact, in some cases, we can achieve shorter code than the mutable version if we do it this way! Of course, this depends on the problem, but it is not wrong to say that it can be achievable.

Creating New Nodes

If you think about it, the difference between the non-persistent and the persistent version is that the former mutates an array called st[] while the latter returns a new node at every build. You can implement this a couple of ways. A famous way is to use a node class. But for me, the way I usually implement it is by allocating a pooled array:

int l[SIZE], r[SIZE], st[SIZE], NODES = 0;
int newleaf(int value) {
    int p = ++NODES;
    l[p] = r[p] = 0; // null
    st[p] = value;
    return p;
}
int newparent(int lef, int rig) {
    int p = ++NODES;
    l[p] = lef;
    r[p] = rig;
    st[p] = st[lef] + st[rig]; // immediately update value from children
    return p;
}

There are two operations, newleaf() and newparent(). We either construct nodes as a leaf or as a parent, where being a parent already pulls values from the children. In the same way as the mutable version, we have an array called st[] that stores the segment tree values depending on our queries. Each node also has pointer to the left and the right children stored at l[] and r[] respectively. For the size, I usually allocate around $SIZE \approx 8N \lceil log N \rceil$. In practice I do this because it's faster than using classes. But of course, it all depends on your groove :)

What about updating nodes? When there's no persistence, we usually directly manipulate our segment tree array st[] like so:

Point Update (usual segment tree)

void update(int i, int x, int p=1, int L=0, int R=n-1) {
    if (L == R) {st[p] = x; return;}
    if (i <= M) update(i, x, 2*p, L, M);
    else update(i, x, 2*p+1, M+1, R);
    st[p] = st[2*p] + st[2*p+1];
}

If we want to add persistent update, we simply need to create new nodes via our newleaf() or newparent() functions instead of the usual assignment operators:

Point Update (persistent segment tree)

// return an int, a pointer to the new root of the tree
int update(int i, int x, int p, int L=0, int R=n-1) {
    if (L == R) return newleaf(st[p] + x);
    if (i <= M) return newparent(update(i, x, l[p], L, M), r[p]);
    else        return newparent(l[p], update(i, x, r[p], M + 1, R));
}

// Usage:
// int new_version_root = update(i, x, root);
// Both roots are valid, you can query from both of them!

The only change you need is wrapping the change in a new node at every update. If we merely consider persistence as a wrapper, we can make the implementation clean and concise.

Range Copy (persistent segment tree)

(Bonus) My favorite operation on a persistent tree is the range copy. This is the ultimate version control technique one can pull off with regards to reverting a range back to a certain version. Imagine doing a range reset back to initial values - what a breakthrough! Although I find it rare to see problems that need range copy (e.g. OAK), it's one of those operations that can come in handy. Fortunately, for a persistent tree, this can easily be achieved a few lines of code:

// revert range [a:b] of p
int rangecopy(int a, int b, int p, int revert, int L=0, int R=n-1) {
    if (b < L || R < a) return p; // keep version
    if (a <= L && R <= b) return revert; // reverted version
    return newparent(rangecopy(a, b, l[p], l[revert], L, M),
                     rangecopy(a, b, r[p], r[revert], M+1, R));
}

// Usage: (revert a range [a:b] back to an old version)
// int reverted_root = rangecopy(a, b, root, old_version_root);

We pass in two roots: the current tree root and the old version root. We traverse both side-by-side, and replace only the relevant nodes during our traversal. This meek five-lined function is the foundation of efficient version-control, which is but one of the many operations you can do with a persistent segment tree.

Complexity

In a usual tree, we change at most $O(log N)$ nodes during an update/query. Therefore, for a persistent tree, we create at most $O(log N)$ nodes as well.

Summary

Persistence is a powerful tool, but can also be made simple. After reading this, I hope that you have come to understand persistent data structures in new light. Trust me, the conversion process is really simple since we just convert all assignment operators to new leaves or parents.

Persistence is not only for segment trees - you can in fact use this technique for other data structures, such as BBSTs. By understanding persistence more generally, I purposefully omitted range query since I want you to try and code that on your own. By now, I hope you can find it easier to come up with your own code for various kinds of queries, and even for lazy propagation! Feel free to comment on this thread to open discussion of such techniques.

As for other resources, you can check out Anudeep's blog or the Wiki page for a more in-depth explanation of persistent trees, explained with problems to solve. With lots of practice, you can be ready hike your way to conquer next month's long challenge. Remember to stay persistent, and happy coding :)

UPD: added usage

UPD2: added list of problems in the comments below!

snackdown'17 qualifer certificates?????

$
0
0

when will we get the snackdown 2017 qualifer round certificates????

chef and sign sequences

Wrong Rank in Snackdown 2017 Certificate

$
0
0

I got rank of Snackdown Pre-Elimination Round A on my certificate of codechef snackdown 2017.
Whereas I got better rank in Snackdown Pre-Elimination Round B.
So, why did I get rank of pre-elimination round A, not of pre-elimination round B on my certificate, as both rounds were of same level?

can set of pairs can be created?


getting wrong ans

ADACRA - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Alei Reyes
Primary Tester:Hussain Kara Fallah
Secondary Tester:Kacper Walentynowicz
Editorialist:Hussain Kara Fallah

DIFFICULTY:

Cakewalk

PREREQUISITES:

None

PROBLEM:

Given a string consisting of characters U,D. In a move you can select a consecutive substring and flip all characters belonging to. (U changes to D and vice versa). What's the minimum number of moves to make all characters equal?

EXPLANATION:

The first thing that will come up to our minds is that we should split the string from the beginning into a block of consecutive 'U' characters, followed immediately by a block of consecutive 'D' characters, then a block of 'U' characters, then a block of 'D' characters... etc. (Of course if our string starts with D then the letters are the opposite). And flip the D blocks.

The number of D blocks = (The number of U blocks) or (the number of U blocks + 1)

If our string starts with D then

The number of U blocks = (The number of D blocks) or (the number of D blocks + 1)

so our answer would be [number of blocks / 2] (of course rounded down).

Example:

Consider our string was "UUUDDUUUDDDUU"

We would split it into :

[UUU] , [DD] , [UUU] , [DDD] , [UU]

The best solution is to flip [DD] , [DDD]

Another Example :

Consider our string was "DDDUDDUU"

We would split it into :

[DDD] , [U] , [DD] , [UU]

Here because the number of U blocks is equal to number of D blocks then flipping the blocks of any letter would be optimal.

Why is this always correct?

If we are looking for a better solution than the mentioned above, then we should flip at least 2 of our targeted blocks at once. But that's impossible because we would affect at least one proper block between them (consisting of characters equal to our final character) and we must return it to its original state again and that's impossible without an additional move.

Consider we tried to obtain a better strategy in the first example:

That means that we would change all D letters to U in one move. It's only possible by flipping the substring [DDUUUDDD] (or any substring formed by extending this one from left or right), but doing this would change U letters to D and we need to return them back to U, and this will cost us at least one operation.

AUTHOR'S AND TESTER'S SOLUTIONS:

AUTHOR's solution: Here
TESTER's solution: Here

Help with this code!? Stuck from Long Time(Someone?)

$
0
0

I have been trying to solve the Gross Salary(FLOW011) problem under beginner section. I have written a code which is working fine for the inputs given in the page but the codechef compiler is showing error, can someone please point out the error.

(UPDATED) Still it's giving same error. Here is the code.

   import java.util.Scanner;

class Flow011 {
public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    double n = in.nextDouble();
    while(n-->0){
        int  salary = in.nextInt();
        double gross;
        if(salary<1500){
            gross = salary+(salary*0.1)+(salary*0.9);
        }
        else{
            gross = salary + 500 + (salary*0.98);
        }
        if(gross==Math.floor(gross)){
            System.out.println((int)gross);
        }
        else
        System.out.printf("%g\n",gross);
    }

    in.close();
}
}

Weak test cases in HISTOSIM

$
0
0

https://www.codechef.com/ISCC2017/problems/HISTOSIM

In the problem HISTOSIM, the following test case should fail:

abcdefghijklmnopqrstuvwxyz bacdefghijklmnopqrstuvwxyz

Since all 26 characters of the alphabet are used there is no "temp" element to use for substitution in changing one string into another.

Help with this problem??(Beginner Section)

$
0
0

I have been trying to solve the Reverse the Number(Flow007) in the beginner section. I have written a code and tried running in the codechef compiler against the input and it is giving wrong answer, it's giving correct output when i tried runing it in eclipse

import java.util.Scanner;

class flow007 {

public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    while(n-->0){
    String num = in.next();
    int len = num.length()-1;
    for(int i = len;i>=0;i--){
        char c = num.charAt(i);
        System.out.print(c);
    }
    System.out.println("");
    }
    in.close();
}
}
Viewing all 39796 articles
Browse latest View live


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