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

What the function 'std::ios_base::sync_with_stdio()' does?

$
0
0

Why do some people use std::ios_base::sync_with_stdio(false) at the beginning of their programs? What do this function do? Why when I remove the function I don't see any difference? Are there some benefit of using the function?


User Account @ CodeChef

$
0
0

@admin I have logged in with my account at CodeChef then why i am seeing other user name in CodeChef Discuss?

rashedcs

Different type of Bug

$
0
0

Here is a new bug I found today about 2-3 times.

Image

There is a random username everytime I open the top contibutor's list on the top left side instead of showing up my name. Even the standing page is according to the random username.

@admin please look into the matter.

Help needed for INOI 2017.

$
0
0

I am in class 8 and I gave ZIO this year and I am getting a score 55-60 so I'll probably qualify. But I want to ask that how to prepare for INOI.

I currently know Python, Javascript, HTML and CSS and just started to learn C++ for INOI.
I have done about 150-160 problems on codechef using python. I know topics like binary search, merge sort, selection sort, insertion sort and a bit of dp.
I am learning c++ completely from youtube.
I am learning data structures and algorithms from places like khan academy, youtube, iarcs, commomlounge etc.
I tried to do some online courses but I can't do a course for more than 1 day. I just don't understand it.
I also don't quite understand from books.

Now, so from where should I learn and prepare.

CHEFARRP - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Misha Chorniy
Tester:Jingbo Shang
Editorialist:Pushkar Mishra

DIFFICULTY:

Simple

PREREQUISITES:

None

PROBLEM:

Given an array, we have to report the number of subarrays such that the product of all numbers in that subarray is equal to the sum of all numbers in that subarray.

EXPLANATION:

The problem is very direct given the size of the input array. Since $n \leq$ 50, we can directly iterate over the subarrays and calculate product and sum. The editorialist's solution is very clear in describing the approach. Below is the pseudo-code of the same:

function get_ans(input_array[n])
{
    int count = 0;
    for(i = 1 to n)
    {
        int sum = 0, product = 1;

        for(j = i down_to 1)
        {
            //considering all subarrays ending at i.

            sum = sum + input_array[j];
            product = product*input_array[j];

            if(sum == product)
                count = count+1;
        }
    }

    return count;
}

COMPLEXITY:

$\mathcal{O}(n^2)$ per test case.

SAMPLE SOLUTIONS:

Author
Tester
Editorialist

Virtual Contest on Codechef

Tim Sort vs Merge Sort

$
0
0

Which is better Tim sort or Merge sort?
And why is Tim Sort not so common?
Python uses it.

Tim sort-
Best case - O(n)
Average case - O(n log n)
Worst case - O(n log n)

Merge sort-
Best case - O(n log n)
Average case - O(n log n)
Worst case - O(n log n)

Writing Interactors and Checkers on Codechef

$
0
0

I'm having trouble writing interactors on codechef platform. Can anyone who has written an interactor for a codechef problem show a sample of an interactor? Thanks.

UPD : I'm also facing problems on writing a working checker.

UPD : For writing an interactor, I used #include "spoj_interactive.h", but even including this header throws errors about some variables being already defined.


TTENIS - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Istvan Nagy
Tester:Kevin Atienza and Gedi Zheng
Editorialist:Kevin Atienza

PREREQUISITES:

Ad hoc, string processing

PROBLEM:

In table tennis, a game is won by the player first scoring 11 points except in the case when both players have 10 points each, then the game shall be won by the first player subsequently gaining a lead of 2 points.

Given a valid, finished game in which Chef is one of the players, determine if Chef won.

QUICK EXPLANATION:

There are many solutions. Here are a few simple ones:

Solution 1: Print "WIN" if the last character in $S$ is a '1', otherwise print "LOSE".

Solution 2: Print "WIN" if there are more 1s than 0s in $S$, otherwise print "LOSE".

EXPLANATION:

This is a simple problem. First, note that the sequence of results of the matches is valid and finished. This means that the winner has been determined at the end (and only right after the last match), and the winner has a lead of at least two points from the loser. This means the following:

  • The last match is won by the overall winner of the contest.

  • At the end, the winner has won more matches than the loser, and so all we have to do is to check if Chef has won more matches than his opponent!

But each of these facts give us an algorithm to compute the answer!

  • If the last match is won by the overall winner, then all we have to do is to check if Chef has won the last match!
  • If, at the end, the winner has won more matches than the loser, then all we have to do is to check if Chef has won more matches than his opponent!

Here is an implementation of the first algorithm, in C++:

#include <iostream>
#include <ios>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    int z;
    cin >> z;
    while (z--) {
        string s;
        cin >> s;
        cout << (s[s.length()-1] == '1' ? "WIN\n" : "LOSE\n");
    }
}

and in Python:

for cas in xrange(input()):
    print "WIN" if raw_input()[-1] == '1' else "LOSE"

There's also a one-liner code-golf in Python:

print'\n'.join(["LOSE","WIN"][input()&1]for _ in range(input()))

Also, here is an implementation of the second algorithm, in C++:

#include <iostream>
#include <ios>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    int z;
    cin >> z;
    while (z--) {
        string s;
        cin >> s;
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            total += s[i] - '0';
        }
        cout << (total * 2 > s.length() ? "WIN\n" : "LOSE\n");
    }
}

and in Python:

for cas in xrange(input()):
    s = raw_input()
    print "WIN" if 2*sum(map(int, s)) > len(s) else "LOSE"

What if there are additional matches?

Let's consider a follow-up problem. Suppose that Chef and his opponent continued after the winner has been determined, i.e. assume there are matches after the winner has been determined.

In this case, we cannot do the strategies above anymore, because it might happen that the Chef lost the game, but his opponent didn't take the following matches seriously so Chef won a lot of matches afterwards. In this case, we now have to determine at which point the winner has been determined, and stop there. We just have to remember that the winner has been determined if someone has scored at least 11 points and has gained a lead of at least two against the other opponent.

Here's an implementation in C++:

#include <iostream>
#include <ios>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    int z;
    cin >> z;
    while (z--) {
        string s;
        cin >> s;
        int s0 = 0, s1 = 0;
        for (int i = 0; i < s.length(); i++) {
            (s[i] == '1' ? s1 : s0)++;
            if (max(s0, s1) >= 11 and abs(s0 - s1) >= 2) break;
        }
        cout << (s1 > s0 ? "WIN\n" : "LOSE\n");
    }
}

and in Python:

for cas in xrange(input()):
    s = [0,0]
    for c in map(int, raw_input()):
        s[c] += 1
        if max(s) >= 11 and abs(s[0] - s[1]) >= 2:
            break
    print "WIN" if s[1] > s[0] else "LOSE"

Time Complexity:

$O(|S|)$

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter
Tester 1
Tester 2

Data Structure Tutorial : Stack

$
0
0

Overview:
Stack is data structure where elements is inserted at the top of the list and any element is deleted from the top of list. So it is called LIFO data structure.Insert operation on a stack is often called push and delete operation is often called pop.

The following picture top is an indicator that indicates the top element of the stack.alt text

Real life applications of stack:
There are many real life example of stack. In our daily life, we see stack of plates in cafeteria or restaurant, stack of the books in book shop. The palate which is at the top is the first one to deleted. Similarly the plate which is at the bottom most is the last one to be deleted.

Operation :
The following operation are performed in the stack.
1. Push : To add an element to a stack.
2.Pop : To remove an element from the stack.
3.Peek : To get the topmost element.

Implementation :
Stack can be implemented two ways. using array and using linked list.Here we discuss stack implementation using array. The stack which is implemented using array array is called array based stack. It uses top variable to print the top most element in the linear array.

1. Initially top=0
2. In Push operation top is increased by one and pushed item to stack[top]
3. In Pop operation top decrease.
4. In Peek operation check that the top is not zero and return stack[top].

 Algorithm : Push(stk, n, item)
 Step 1: Start
 Step 2: if(top==n)        print overflow
         else              stk[top++]=item.
 Step 3: End

C++ implementation :void push(int stk[],int n,int item){if(top==n)  cout<<"Overflow"<<endl;else        stk[top++]= item;}


 Algorithm : Pop(stk)
 Step 1: Start
 Step 2: if(top==NULL)  print Underflow;
         else           top--;
 Step 3: End
C++ implementation :void pop(int stk[]){if(top==NULL)    cout<<"Underflow"<<endl;else top--;}

 Algorithm : Peek(stk)
 Step 1: Start
 Step 2: if(top==NULL)  print Underflow;
         else           return stk[top-1];
 Step 3: End
C++ implementation :int peek(int stk[]){if(top==NULL)    cout<<"Underflow"<<endl;elsereturn skt[top-1];}

Stack has many application . We can convert an infix into post-fix expression using stack. We can explain this. We start to scan the expression from left to right. In an expression , there may be some operands, operators and parenthesis.

Steps:
 1. If a symbol is an operand add it to the post-fix expression.

 2. If the symbol is an opening parenthesis push it on the stack.

 3. If the symbol is an operator.Then check the top of the stack.
   (i) If the precedence of the operator at the top is higher or same as the current operator     then repeatedly it is popped and added to the post-fix expression.
  (ii) Else it pushed onto the stack.

 4.If the symbol a closing parenthesis then
   (i) Repeatedly pop from the stack and add each operator to the postfix expression  until the corresponding opening encountered.
  (ii) Remove the opening parenthesis from the stack.
C++ implementation :void prefex2postfix(string s){
      stack<char>st;for(int i=0; i<s.length(); i++){if(isdigit(s[i])||isalpha(s[i]))  cout<<s[i];elseif( s[i]==')'){while(st.top()!='('){
                    cout<<st.top();
                    st.pop();}
             st.pop();}else st.push(s[i]);}}

Stack full source code : link

Codechef Problem : ONP , BEX
Spoj Problem STPAR , Transform the Expression
Hackerrank : Balanced Brackets

ACBALL - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

Contributors

Author:Amit Pandey
Tester & Editorialist:Prateek Gupta

DIFFICULTY:

Simple

PREREQUISITES:

None

PROBLEM:

Given two strings $X$ and $Y$ of length $N$, form another string $Z$ of same length such that the hamming distance($X$, $Z$) + hamming distance($Y$, $Z$) is maximized. If there are many such types of $Z$ possible, print the lexicographically smallest one.

EXPLANATION


Solution for Subtask 1:
This subtask can indeed be solved by Bit Masking. We can generate all possible strings where each character will be either 'W' or 'B'. For each such string, we can track the maximum sum of hamming distances and the corresponding string which gave us the new maximum. In case, we have the same maximum, it is fine to compare the string and store the one which is lexicographically smaller. Lets look at the pseudo code to understand how this works.

F(N, X, Y) {
     string Z;
     int max_val = -1
     for mask in range(0, 2^N) {
          string tmp = ""
          int hamming_sum = 0
          for i in range(0, N) {
              if ( bit i is set in mask ) tmp.append('W')
              else tmp.append('B')
              hamming_sum += (tmp[i] != X[i]) + (tmp[i] != Y[i])
              if ( hamming_sum > max_val )
                 max_val = hamming_sum, Z = tmp
              else if ( hamming_sum == max_val )
                  Z = min(Z, tmp)
          }
     }
     return Z
}


Solution for subtask 2 & 3:
In order to maximize the sum of hamming distance between string ($X$, $Z$) and string ($Y$, $Z$), we can greedily decide to fill each position of $Z$ with either 'B' or 'W'. At each position, there are only two possible cases for us to consider.

  • If $X_{pos}$ and $Y_{pos}$ are same, the best decision will be to insert the character which is not equal to $X_{pos}$ or $Y_{pos}$ since it will fetch you a value of +2 to your sum of hamming distances.
  • If $X_{pos}$ is not equal to $Y_{pos}$, then you can insert any character since it will fetch you a value of +1. But, you also need to make your string $Z$ lexicographically smaller. Hence, you should insert character 'B' since 'B' < 'W' in terms of lexicographical nature.

Fore more details on the implementation of any of the subtasks, have a look at the tester's solution.

COMPLEXITY

As the string $Z$ can just be found in a single traversal, the overall time complexity of the solution is $\mathcal{O}(N)$.

SOLUTIONS

Setter
Tester's solution to Subtask 1
Tester's solution to Subtask 2

Challenge problem rejudge

$
0
0

Although the challenge problems have been rejudged.. The new scores of the participants have not been updated in the the rank list and therefore, we dont know our actual rank. I just wanted to know my rank so as to check whether i am amongst top20 indians or not. Someone please help. Thank you.

Competive programming language: C++ vs Java

$
0
0

Which is the better programming language for competitive programming : C++ vs Java?

Data Structure Tutorial : Queue

$
0
0

Overview:
Queue is a data structure where elements is inserted at the front of the list and any element is deleted from the rear of list. So it is called FIFO(First in First out) data structure.
Insert operation on a queue is often called enque and delete operation is often called deque.
If we insert an element to queue the rear is increment. Similarly If we delete an element from queue the front is increment.

The following picture front is an indicator that indicates the front element of the queue and rear is also an indicator that indicates the last element of the queue.alt text

Real life applications of stack:
Queues abound in everyday life. In our daily life, when we stand on line to get into bus , we make queue. The man who stands first will get into bus first and the man who stand last will get into the bus last.

Operation :
The following operation are performed in the stack.
1.Enque : To add an element to queue. 2.Deque : To remove an element from the queue. 3.Peek : To get the topmost element in queue.

Implementation :
Queue can be implemented two ways. using array and using linked list.Here we discuss queue implementation using array . It uses front variable to print the top most element and rear variable to print the bottom most element in the linear array.

  1. Initially front=rear=0
  2. In Enqueue operation rear is increased by one and pushed item to queue[rear]
  3. In Deque operation front is increased by one. i.e queue[front++]
  4. In Peek operation check that the front is not equal to rear and return queue[front]

  Algorithm : Enqueue(que, n, item)
  Step 1: Start
  Step 2: if(rear==n)         print overflow
           else               que[rear++]=item.
  Step 3: End
C++ implementation :
    void Enque(int que[],int n, int item)
    {
      if(rear==n)  cout<<"Overflow"<<endl;      else        que[rear++] = item;    }

  Algorithm : Deque(que)
  Step 1: Start
  Step 2: if(front==rear)  print Underflow;
          else             que[front++];
  Step 3: End

C++ implementation :
    void Deque(int que[])
    {
      if(front==rear)    cout<<"UnderFlow"<<endl;
      else               que[front++] ;
    }


  Algorithm : Peek(que)
  Step 1: Start
  Step 2: if(front==rear)    print Empty;
          else               return que[front];
  Step 3: End
C++ implementation :
    int Peek(int que[])
    {
      if(front==rear)    cout<<"Queue is empty"<<endl;
      else               return que[front];
    }

Spoj Problem: ADAQUEUE
Hackerrank Problem :Queue using Two Stacks

Programming Contest

$
0
0

Hi everyone, Competitive Programming present you their first programming contest Go-pro.

A programming contest series where you will be able to solve some interesting problems.

Please do participate and show your skills.

Contest link : https://www.hackerrank.com/gopro-1

Duration : Nov 24 2016, 08:00 pm IST to Nov 24 2016, 11:30 pm IST

Please participate and share it and have fun with some good problems.

Keep code!


How to get internship at codechef?

$
0
0

I want to know how to get internship at codechef.

Prize in November Lunchtime 2016?

$
0
0

Are there any prize given in November Lunchtime 2016(to the top scorer)?

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.

How fair is the Top Contributors list?

$
0
0

Codechef discuss forum is a very nice community. I have also answered some basic questions on it. But, since past few days I see some people deliberately upvoting all the old answers of their friends so that their friends can go up in top contributors list. It seems like people are more concerned about convincing their friends to upvote their answers than really helping people and learning through the community.

This is not the first time such thing happened, take a look at this thread. This is really frustrating now. Here are the observations since yesterday.

@haresh_kh got more than 20 upvotes : 4 from @adkroxx, 3 from @hm_98, 4 from @deva2802, 3 from @sahil_g, 3 from @tirth14, 2 from @ketanhwr, 1 from @aka38

@hm_98 got more than 19 upvotes : 6 from @adkroxx, 6 from @deva2802, 3 from @haresh_kh, 3 from @sahil_g, 1 from @aka38

@sahil_g got more than 19 upvotes : 5 from @adkroxx, 4 from @aka38, 5 from @hm_98, 5 from @haresh_kh

The most intresting part is they are all from IIT Roorkee. This observation is only since yesterday not full month. Is this fair?

Test Cases for Contest Problems can be revealed after the contest!

$
0
0

There are many people whose solution fails for few test cases and hence get partially correct answers in the contest.

For Ex: Many people have got 85 points in LIGHTHSE and 60 points in REBXOR in the September Long Contest which means they have all failed to pass the 1st Subtask which might have contained some special/boundary cases.

To help people know their mistakes Codechef can post the Test Cases along with the editorial as people will be able to identify the mistakes in their own code which will be of great help.

Please upvote if you feel this is good idea! :)

@admin : Let us know your opinion too.

Viewing all 39796 articles
Browse latest View live


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