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

Why do I get an NZEC?

$
0
0

Why m i getting NZEC (Non Zero Exit Code) for my program?


MSTQS - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Pawel Kacprzak
Tester:Misha Chorniy
Editorialist:Pawel Kacprzak

DIFFICULTY:

MEDIUM

PREREQUISITES:

Graph theory, Minimum Spanning Tree, Kruskal's algorithm

PROBLEM:

This problem is all about Minimum Spanning Tree, which we call $MST$ here. For a given graph $G$ with $N$ vertices and $M$ weighted edges, the goal is to handle $Q$ queries. Each query can either assign $0$ weight to given existing edge in $G$ or assign to a given edge its original weight, or ask for the weight of $MST$ of the current graph $G$.

QUICK EXPLANATION:

Take a closer look at how does Kruskal’s algorithm work and notice that the answer for each query asking for the weight of the current $MST$ can be computed by running Kruskal’s algorithm only on edges with zero weight and edges in the initial $MST$ of $G$.

EXPLANATION:

Subtask 1

In the first subtask we have $N \leq 200, M \leq 2000$ and $Q \leq 2000$, so we can just keep track of the current weights of the edges while performing queries and for each query asking for the weight of the current $MST$, we can run any fast algorithm computing $MST$ from the scratch, for example Kruskal’s algorithm. This solution has time complexity of $O(Q \cdot f(N, M))$, where $f(N, M)$ is the complexity of used $MST$ algorithm on a graph with $N$ vertices and $M$ edges. Notice that this results in $O(Q \cdot M \cdot \log^*(M))$ time for Kruskal's algorithm even when full sorting is performed only at the beginning.

Subtasks 2 and 3

In these subtasks we have $N \leq 2000$, $M \leq 2 \cdot 10^5$ and $Q \leq 20000$.

The following approach can be used to solve both of these subtasks, the only difference is that in the last subtask one have to handle restoring original weights of edges, which is just a little bit more straightforward implementation.

Let’s first compute $MST$ of the initial graph before performing any queries and let $T$ be this $MST$. The crucial observation is that at any point while handling the queries, the weight of the $MST$ of the current graph can be computed by running Kruskal’s algorithm on edges with zero weight at this point and edges of $T$.

Why is this observation correct? Well, if we take a closer look at how does this algorithm work, we can see that it iterate over a list of given edges in ascending order of their weights and put the current edge into the result if and only if it connects not yet connected components of $G$. So if we run it on edges with zero weight and edges from $T$, it will merge some components using some of these zero edges first and then try edges from $T$ if necessary. Since the algorithm is only merging components, it follows that no edge not it $T$ with non-zero edge at this point will be used by the algorithm, because after processing edges with zero weights, some edges from $T$ might not be needed, but if any two components still require to be merged, the algorithm will do it with an edge from $T$ just as it did in the initial graph.

Thus in order to solve the problem, one can maintain the list of edges with zero weights updating it when necessary - this can be done in $O(1)$ time if for example a linked list is used, and for each query asking for the weight of the current $MST$ run Kruskal’s algorithm on at most $O(Q + N)$ edges. Theoretically this results in $O(Q \cdot (Q + N) \cdot \log^*(N))$ complexity, but notice that in order for $K$ zero edges to be processed by the algorithm, we have to perform $K$ queries adding them first, so the factor of $Q^2$ is divided by some constant of at least $4$ here.

AUTHOR'S AND TESTER'S SOLUTIONS:


Setter's solution can be found here.
Tester's solution can be found here.

FLYMODE - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Pawel Kacprzak
Tester:Misha Chorniy
Editorialist:Pawel Kacprzak

DIFFICULTY:

SIMPLE

PREREQUISITES:

Sorting, sweep line

PROBLEM:

For a list of $N$ positive consecutive heights: $h_1, h_2, \ldots, h_N$ denoting some heights at which a plane was during its flight and knowing that between heights $h_i$ and $h_{i+1}$ it was flying the shortest path between these height, which means it was at every height between these two ones once, find the maximum integer $K$, such that the plane was $K$ times at some height during the flight.

QUICK EXPLANATION:

For every pair of consecutive heights $h_i, h_{i+1}$ add each of these heights as either opening or closing time event to a list of all events, let’s call it $E$, happening in time. Sort $E$ and process it using sweep line keeping track of the number of current opened events that has not been closed. The result is the maximum number of opened events during this process.

EXPLANATION:

Subtask 1

In this subtask $N$ is at most $1000$ and we know that each $h_i \leq 1000$. This allows the following approach:

Let $K$ be the result to the problem and $H$ be the set of some candidate heights such that the plane was at some $h \in H$ exactly $K$ times. If $H$ is not too big, then we can for each $h \in H$ check how many times the plane was at height $h$ by iterating over all two consecutive input heights $h_i, h_{i+1}$ and counting the number of such pairs that contain $h$. The answer to the problem is the maximal such count. This approach has the time complexity of $O(|H| \cdot N)$, but how to chose $H$? Well, we can take advantage of the fact that $h_i \leq 1000$. Important thing to notice is that the height on which the plane was the most number of times can be a real number, not integer. However, the crucial observation is that we can put to $H$ all positive integers not greater than $1000$ and also floating points exactly between them, so $1.5, 2.5, \ldots$. Is turns out that these candidate heights are sufficient because all input heights are integers.

Subtask 2

In the second subtask $N$ can be at most $10^5$ and each $h_i \leq 10^9$, so method described above will take too much time. The crucial observation to approach the problem is to notice that if $K$ is the answer to the problem, there exists height $h$ for which there exists $i$ such that $\min(h_i, h_{i+1}) \le h \le \max(h_i, h_{i+1})$ and the plane was at height $h$ exactly $K$ times. Thus the problem can be reduced to finding a point which is covered by most of these height pairs and returning the maximum size of such cover. Let’s think of pairs of consecutive heights as segments from the smaller to the larger height. Notice that changing height from $h_i$ to $h_{i+1}$ corresponds to one such segment. Moreover, the reduced problem can be easily solved using a sweep line algorithm by sorting all endpoints of the segments, then processing them from left to right counting the number of opened segments and returning the maximal such count during this process. The complexity of this solution is $O(N \cdot \log(N))$ dominated by the sorting phase.

AUTHOR'S AND TESTER'S SOLUTIONS:


Setter's solution can be found here.
Tester's solution can be found here.

DP for INOI

$
0
0

I am struggling to get good problems on DP at a similar level to that of INOI. I know of a2-online judge's categories, but not all problems there are good.(I currently solve level 4 problems). So, I would like you to enlist some DP tutorials and problems for practicing for INOI as it is the most common topic asked in INOI. I already know of mit ocw DP lectures and Topcoder's tutorial.

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?

WDTBAM - Editorial

$
0
0

Problem Link

Practice
Contest

Difficulty

CakeWalk

Pre-requisites

Basic programming language constructions

Problem

Find the maximal value of the profit for playing a single-player game described in the problem statement

How to get 20 points

Let's generate all permutations of the order of the questions and calculate the score for each of them. Among the scores for all the orders, choose the maximal. Then just output the maximal obtained score. Since there are exactly N! permutations of the set of N questions and a check of a single order takes O(N) time, the complexity of such a solution is O(N!*N).

In C++ you can use STL routine next_permutation for simple generation of all the permutations.

This solution solves the first subtask, however, it is too slow to get the full points.

How to get 100 points

Let us calculate K - the number of the questions that would be answered correctly by Chef. Clearly, the ith question will be answered correctly if the ith sumbol in the first string equals to the ith symbol in the second string.

If K = N, there is no other option than Chef answers all the questions correctly and gets WN dollars of profit.

Otherwise, using any question than can be answered incorrectly, we can obtain any number of correct answers between 0 and K inclusively. Then the answer is, therefore, the maximal value of Wi for 0 ≤ i ≤ K.

The complexity of such a solution is O(N) for a single test case.

Setter's Solution:

Can be found here

Tester's Solution:

Can be found here

Why do I get Wrong Answer?

$
0
0

Why is my program getting wrong answer?

Help me Debugging my code


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

Data Structure Tutorial : Array

$
0
0
If you find any error please comment. I will try to update this post.              Array is a collection of homogeneous data elements. It is a very simple data structure. The elements of an array are stored in successive memory location. Array is refered by a name and index number. Array is nice because of their simplicity and well suited for situations where the number is known. Array operation :

Traverse
Insert
 Delete
Sort
Search


There are two types of array. One dimensional array and multi dimensional array.One dimensional array This type of array of array represent and strore in linear form. Array index start with zero.

Declaration : datatype arrayname[size];int arr[10];

Input array :for(int i=0; i<10; i++)  cin>>arr[i];

We can use store integer type of data to the array arr using above segment.----------

Traverse : Traversing can easy in linera array. Algorithm:


C++ implement :void traverse(int arr[]){for(int i=0; i<10; i++)   cout<<arr[i];}----------

Insertion : Inserting an element at the end of a linear array can be easily done provided the memory space space allocated for the array is large enough to accommodate the additional element. Inserting an element in the middle .. Algorithm : Insertion(arr[], n, k, item) here arr is a linear array with n elements and k is index we item insert. This algorithm inserts an item to kth in index in arr.

Step 1:Start
Step 2: Repeat for i=n-1 down to k(index)
   Shift the element dawn by one position] arr[i+1]=arr[i];[End of the loop]
Step 3: set arr[k]= item
Step 4: n++; Step 5: Exit.


C++ implement :void insert(int arr[],int n,int k,int item){for(int i=n-1; i>=k; i--){
         arr[i]=arr[i+1];}
      arr[k]= item;
      n++;}----------

Deletion : Deletion is very easy on linear array.

Algorithm : Deletion(arr, n, k) Here arr is a linear array with n number of items. K is position of elememt which can be deleted.
Step 1:Start
Step 2: Repeat for i=k upto n[Move the element upword]  arr[i]=arr[i+1];[End of the loop]
Step 3: n--;
Step 4: Exit.


C++ implementation :void deletion(int arr[],int n,int k){for(int i=k; i<n; i++){
            arr[i]= arr[i+1];}
      n--;}----------

Searching : Searching means find out a particular element in linear array. Linear seach and binary search are common algorithm for linear array. We discuss linear search and binary search.

Linear search Algorithm : Linear search is a simple search algorithm that checks every record until it finds the target valueAlgorithm: LinearSeach(arr, n, item)
Step 1:Start.
Step 2: Initialize loc=0;
Step 3: Repeat for i=0 upto n-1if(arr[i]==item) loc++;[End of the loop]
Step 4:if loc is not zero then print found otherwise print not found.
Step 5: Exit.

C++ implementation :void linear search(int arr[],int n, item){for(int i=0; i<n-1; i++){if(arr[i]==item) loc++;}if(loc) cout<<"Found"<<endl;else cout<<"Not found"<<endl}----------

Binary search : Binary search is available for sorted array. It compares the target value to the middle element of the array;if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful.

Algorithm : BinarySeach(arr, n, item)
Step 1:Start
Step 2: Initialize low =0 and high = n-1;
Step 3: While loop low<=high
    mid =(low + high)/2;if(a[mid]== item)return mid;elseif(a[mid]< item) low = mid +1;else high = mid -1;
Step 4: If item is not found in array return-1. Step 5: End.


C++ implementation :int binarySearch(int[] a,int n,int item){int low =0;int high = n -1;while(low<=high){{int mid =(low + high)/2;if(a[mid]== item)return mid;elseif(a[mid]< item) low = mid +1;else high = mid -1;}return-1;}--------------------
Sorting : There are various sorting algorithm in linear array. We discuss bubble sort and quick sort in this post.
Bubble Sort: Bubble sort is a example of sorting algorithm . In this method we at first compare the data element in the first position with the second position and arrange them in desired order.Then we compare the data element with with third data element and arrange them in desired order. The same process continuous until the data element at second last and last position.

Algorithm : BubbleSort(arr,n)
Step 1:Start
Step 2: Repeats i=0 to n
Step 3: Repeats j=0 to nif(arr[j]>arr[j+1]) then interchange arr[j] and arr[j+1][End of inner loop][End of outer loop]
Step 4: Exit.

C++ implement :void BubbleSort(int arr,int n){for(int i=0; i<n-1; i++){for(int j=0; j<n-1; j++){if(arr[j]>arr[j+1])     swap(arr[j],arr[j+1]);}}}

Quick Sort:
 Quick sort is a divide and conquer paradism. In this paradism one element is to be chosen as partitining element .
We divide the whole list array into two parts with respect to the partitiong elemnt . The data which are similar than or equal to the partitining element remain in
 the first part and data data which are greater than the partitioning element
 remain in the second part. If we find any data which is greater than the partitioning value that will be transfered to the second part., If we find any data whichis smaller than the partitioning element that will be transferred to first part.
Transferring the data have been done by exchanging the position of the the data
found in first and second part. By repeating this process ,
we can sort the whole list of data.Algorithm: QUICKSORT(arr, l, h)if  l<h then pi ← PARTITION(A, l, h)
QUICKSORT(A, l, pi–1)
QUICKSORT(A, pi+1, h)

C++ implementation :int partition(int arr[],int start,int end){int pivotValue = arr[start];int pivotPosition = start;for(int i=start+1; i<=end; i++){if(pivotValue > arr[i]){
          swap(arr[pivotPosition+1], arr[i]);
          swap(arr[pivotPosition], arr[pivotPosition+1]);
          pivotPosition++;}}return pivotPosition;}void quickSort(int arr[],int low,int high){if(low < high){int pi = partition(arr, low, high);
      quickSort(arr, low, pi -1);
      quickSort(arr, pi +1, high);}}






C++ example for simple sorting program with stl function: #include <bits/stdc++.h>using namespace std;intmain(){int  n, arr[100];
   cin >> n;for(int i=0; i<n; i++){
     cin>>arr[i];}

   sort(arr, arr + n);for(int i=0; i<n; i++){
      cout<<arr[i]<<"";}
   cout<<endl;return0;}

Codechef Problem : SMPAIR, Ups and Downs, KTTABLE, TLG ,FORESTGA
Spoj Problem : AGGRCOW - Aggressive cows
Hackerrank Problem : Arrays - DS, Quicksort 1 - Partition, Quicksort 2 - Sorting

Unfair Karma System

$
0
0

I would like to propose a system where members even with 1 karma point are allowed to ask their questions as separate posts and not as comment's on others posts where they are sometimes ignored as they are not even seen there.
I've been an active user of CodeChef since Oct,15 and there have been many times when I've been really confused and frustrated due to this karma system as I couldn't ask any of my doubts or queries at the discussion forum because minimum required points to even ask a question are 3 . It 's like a dumb boy waiting in the class so that someone would ask the same doubt or question he has so that he does not have to face the teacher. Rather here he is not allowed to talk to the teacher and keeps waiting.
I think this forum is not a place where only geeks should talk or ask their questions, it's a place where all learners should ask, ask, ask and learn more and more. Who more than a newbie to competitive programming requires help, or gets confused.
Please @admin look into this matter as soon as possible.
Meanwhile all members who have 1 karma points and want to ask some questions and are not able to do so can comment below, and I would request all members who are reading this post to give them at least 1 upvote so that they do not face this problem anymore if that does not violate any rules or regulations of the forum.

Graph Theory and Dynamic Programming

$
0
0

Hi!
I am preparing for INOI and I am not good at Graph Theory and I want to know how I can become good In Dynamic Programming and Graph Theory for INOI.
So, Kindly provide me some videos and books for it.
Thank's!

doubt--NEED HELP

Topics frequently asked in INOI?

$
0
0

What topics are asked in INOI. I mean what are the most important topic that i should prepare for now?

Request-Please add Keteki Quick Match 4 Questions to Practice Session

$
0
0

Please add this questions,so we can practice this question


Implementation Difficulty in String Problem

modulus and long doubt

make tags invisible

$
0
0

Hey is there any feature to make tags under problems invisible on codechef(similar to the codeforces one ) ?If not it would be a good addition as while seeing time limit tags are seen unwantedly !

January Long Challenge 2017 Schedule

$
0
0

Why there is no schedule of JAN17 posted till now?

What should I do?

$
0
0

I started competitive programing 5 months ago till now I can solve upto 4 to 5 problems in long challenge . I want to improve myself such that , I will be able to solve more problems of Long Contest.

Please help me devise a schedule that a top programmer followed and please do tell me the type of problems I should solve.

Viewing all 39796 articles
Browse latest View live


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