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

for begineers editorial provided by codechef not usefull

$
0
0

i wanna say that the begineers rating(1000-5000) can easily understand the first 4 to 5 problems but after that they struck even after reading the editorial .myself always found difficulty to understand from editorials from codechef becz of having very short explanation .one day i was looking others solution then i came accross a guy named shadik from bangladesh. in every long challenge he do around 4 to 5 question and put the solution on his website;https://shadekcse.wordpress.com/ and after reading solution i found that that is quite simple to grab the logic here he explain well so i request codechef to improve the editorials quality prepare the editorial in such a way that a person having fair knowledge of coding can understand that or their is another way also .that is if good coders from codechef can prepare good quality editorial (vedio link,trick explanation ,minor things) and post it somewhere.then it will be great help to those who wanna learn but can't learn due to lack of proper explanation......gud luck.......... if others are also facing same problem then let me now.... #wanna_learn


INOI Preperation tips

$
0
0

So how are we supposed to prepare for INOI what were the passing cut-offs previous years(2016 and before) and what are the prerequisite topics and what is the most asked topics also some useful links are welcomed.

RESTPERM - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

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

DIFFICULTY:

MEDIUM

PREREQUISITES:

Divide and conquer

PROBLEM:

Given an unknown permutation $A$ of numbers from $1$ to $N$, ask queries of form:

$\texttt{divisible}(x, y, d) := \texttt{true}$ if and only if $|A_x - A_y$| is divisible by $d$
$\texttt{less(x, y)} := \texttt{true}$ if and only if $A_x - A_y$

and find out what the permutation is exactly. The hard part of the problem is the fact that you can ask at most $13 \cdot N$ $\texttt{divisible}$ queries and at most $N-1$ $\texttt{less}$ queries.

QUICK EXPLANATION:

Use divide and conquer and recursion to solve the problem. While there are more than $2$ elements in the instance of a problem, partition them into two almost equal sets using $\texttt{divisible}$ query. Solve the problem for both partitions recursively and merge these sub-results using the less query.

EXPLANATION:

In subtasks $1, 2$ and $3$ the constrains are low enough to allow multiple different approaches. In particular they allow more calls to the $\texttt{divisible}$ query. The general idea behind some of them is also covered in the explanation of the intended solution, so we recommend to read the below detailed explanation of this method.

In the last subtask, the permutation is quite large - it has up to $10^4$ elements. We are going to solve the problem recursively using divide and conquer approach. Notice that when the instance of the problem is very small, i.e. $N \leq 2$, the problem is very easy to solve. In particular, when $N=1$ there is nothing to do, because the partition is already known, and if $N = 2$ then, one $\texttt{less}$ query is enough to determine the permutation. So the question is what to do when $N > 2$? Well, we can use $\texttt{divisible}$ query then. The idea is that we want to partition the initial indices of the permutation into two almost equal in size groups, solve the problem recursively for the partitions and finally somehow combine these result into the final result.

Let $solve(indices, divisor)$ be a recursive function finding out the absolute order of elements of the permutation with indices belonging to $\texttt{indices}$ array and using $divisor$ as the value for $d$ in $\texttt{divisible}$ query to partition the elements. Moreover, the $solve$ function will return the index of the smallest number in the permutation with index in indices - we will be using this element to merge two subproblems solved recursively. The final answer to the problem will be the partition returned by calling $solve([1,2,\ldots,N], 2)$. If there are no more than $2$ indices we know what to do, otherwise we are going to partition indices into two groups $P_1$ and $P_2$ as follows:

  • the first element of the indices array, i.e. $indices_1$ goes into $P_1$
  • the $i$-th element of the indices array, i.e. $indices_i$ goes into $P_1$ if and only if the result of $divisible(indices_1, indices_i, d)$ is $\texttt{true}$, otherwise it goes into $P_2$. In other words it goes to $P_1$ if and only if $|A_{indices_1} - A_{indices_i}|$ is divisible by $d$.

The above method partition the indices into two almost equal in size sets. For example, let’s assume that the initial permutation is $5,3,2,4,1$ and we are solving the problem for all the indices $1,2, \ldots, 5$. Then the partition will assign indices as follows:

$P_1 = \{1, 2, 5\}$
$P_2 = \{3, 4\}$

The index $1$ is in $P_1$ because it is the first element of $\texttt{indices}$. The indices $2$ and $5$ are also in $P_1$ because the results of $\texttt{divisible(1, 2, 2)}$ and $\texttt{divisible(1, 5, 2)}$ are true (for example $|5-3|$ is divisible by $2$). Other elements are in $P_2$ because the result of $\texttt{divisible}$ query for them is $\texttt{false}$.

After the partition, we are going to solve the problems corresponding to the indices in $P_1$ and $P_2$ separately with $divisor$ multiplied by two, so we will call two functions:

  • $solve(P_1, 2 \cdot divisor)$
  • $solve(P_2, 2 \cdot divisor)$

We multiply the divisor by $2$ to allow the partitions performed during these subcalls to be done in the same way. By the definition, these functions returns the absolute orders of the elements in the permutation with indices in $P_1$ and with indices in $P_2$. The only thing left to do is to merge these two orders into the final order. Let $s_1$ be the index of the smallest element in the permutation among elements with indices in $P_1$. Similarly, let $s_2$ be the index of the smallest element in the permutation among elements with indices in $P_2$. These elements are also returned from recursive calls. We are going to use them to merge sub-results into the final result. Notice that if $s_1 < s_2$, then the smallest element, i.e. the element with value $1$ is among the element with indices in $P_1$. Moreover, the $3$rd smallest, $5$th smallest, ... elements among all elements with indices in $\texttt{indices}$ have also indices in $P_1$ and all other elements have indices in $P_2$. In the other case, if $s_2 < s_1$ the situation is opposite and the elements with ranks $1, 3, 5, \ldots$ have indices in $P_2$ and all other elements have indices in $P_1$. Thus calling a query $less(s_1, s_2)$ allows us to determine how to merge the absolute orders of element with indices in $P_1$ and $P_2$ into one absolute order of elements with indices in $P_1 \bigcup P_2$.

Notice that this method calls $\texttt{divisible}$ query at most $13 \cdot N$ times because it calls it no more than $N$ times on each level of recursion tree besides two deeper ones and the recursion tree has depth non greater than $\log N = 14$. Also, this methods calls $\texttt{less}$ query at most $N-1$ times, from the same reason.

AUTHOR'S AND TESTER'S SOLUTIONS:


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

LSTGRPH - Editorial

$
0
0

Problem Link:contest, practice

Difficulty: Easy-Medium

Pre-requisites: DFS, BFS, Bipartite Graphs, Graph Traversal

Problem:

Given a graph G with non-negative values Yj assigned to the edges.

Your task is to find the K'th lexicographically valid sequence (X1, X2, ..., XN) that satisfies to the following condition:

Let's suppose that the j'th edge of G connects vertices Uj and Vj. Then, a non-negative integer Yj equals to XUj xor XVj.

Explanation:

Let's assume, that all the values of Xi and Yj belong to {0, 1}. If it's not true, then we can consider all the bits seperately(since we are working with XOR operation) and reduce the problem to the case, when all the values of Xi and Yj belong to {0, 1}. Let's also assume, that G is connected(otherwise, we can solve the problem in each connected component seperately).

Let's consider some valid sequence (X1, X2, ..., XN). The given graph G is bipartite and divided into two parts: if Xi = 0, then i'th vertex of G belongs to the first part of G, otherwise it belongs to the second part.

What about edges? Let's suppose that the j'th edge of G connects vertices Uj and Vj. Then, if Yj = 0, then Uj and Vj belong to the same part of G, otherwise they belong to different parts. It means, that if we know the value XUj, then XVj = XUj xor Yj.

So, let's build up an algorithm of finding the least lexicographically valid sequence (X1, X2, ..., XN):

  1. Assigning X1 = 0;
  2. Starting BFS(or DFS) from the first vertex;
  3. Calculating the values of Xi while moving along the edges( Xconnected with known = Xknown xor Ythe edge between the current vertices ).

If we have faced some contradictions during the algorithm(i.e. XV should be both 0 and 1 for some vertex V), then there is no valid sequence (X1, X2, ..., XN) at all, otherwise it's found by our algorithm.

As was said before, we can run this algorithm for every bit of Yj's( there are at most 31 of them ) and then merge the results. It's important to note, that for different bits there could be different partitions of G(i.e. the same vertex V could belong to the first part of G while processing the first bit of Yj's and belong the second part of G while processing the second bit of Yj's), but that's OK since there's no limits for that.

Ok, we have just considered an O( (N + M) × log2Y ) algorithm of finding the least lexicographically valid sequence (X1, X2, ..., XN), but we can do better.

Let's solve the problem for all the bits simultaneously, doing exactly the same algorithm as described above. If we have faced some contradictions during the algorithm(i.e. XV should be equal to different values at the same time for some vertex V), then there is no valid sequence (X1, X2, ..., XN) at all, otherwise the least lexicographically valid sequence of X's is found by our algorithm.

That's nice, but we are asked to find the K'th lexicographically valid sequence.

Let's suppose, that (X1, X2, ..., XN) is the least lexicographically valid sequence of X's. Then we can just assign each Xi = Xi xor (K - 1) and get the K'th lexicographically valid sequence of X's. This little trick works because ( XUj xor (K - 1) ) xor ( XVj xor (K - 1) ) = XUj xor XVj = Yj.

Let's denote the minimal vertex of a connected component as a vertex with the minimal index among vertices from the component. If G is not connected, then let's find the least lexicographically valid sequence of X's in every connected component separately. After that, let's find the K'th lexicographically valid sequence in the connected component with the maximal possible minimal vertex. It's not hard to prove, that it's the K'th lexicographically valid sequence for the whole graph G.

The total complexity of the solution is O(N + M).

Please, check out Setter's and Tester's solutions for your better understanding.

Setter's Solution:link

Tester's Solution:link

TOMJERGA - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Praveen Dhinwa
Tester:Animesh Fatehpuria
Second Tester:Kevin Atienza
Editorialist:Pawel Kacprzak

DIFFICULTY:

MEDIUM-HARD

PREREQUISITES:

Trees, LCA

PROBLEM:

In this problem, for a given tree of $N$ nodes the task is to handle $Q$ queries. Each query consists of two vertices $t$ and $j$ denoting the initially positions of respectively Tom and Jerry in the tree. In one second, both Tom and Jerry can and have to change their current positions to one of the adjacent nodes to nodes they are currently in, and Jerry makes the move first, which is followed by Tom’s move. The answer for a single query is the minimum number of seconds Tom needs to catch Jerry, i.e. be in the same vertex as he is no matter how Jerry moves.

QUICK EXPLANATION:

For each query, find the middle of the path from $t$ to $j$. Let’s call this node $v$. Then find the maximum distance from $v$ to it’s subtree where $j$ is also located. The final answer is the sum of this distance and the distance from $t$ to $v$.

EXPLANATION:

Notice that if $v$ is the node exactly in the middle of the path from $t$ to $j$, then Tom can always prevent Jerry from crossing $v$ by just moving greedily towards $v$. Thus the best Jerry can do is to find the longest path from $v$’s located in the same subtree of $v$ that $j$ is in. This observation is crucial and needed to came up with the solution. Exact solution and its time complexity depends on how does one implement these two parts, i.e. finding the middle vertex and the finding the longest path in one of its subtrees. Various approaches can be used to solve each subtask and they are described below. Last but not least thing to mention is that computing the middle vertex can be sometimes tricky, and when implementing it one should for example remember than in each turn Jerry makes his move first.

Subtask 1

In the first subtask we have bot $N, Q \leq 100$. This allows us to make a straightforward simulation of the whole process independently for each query. More specifically, for a single query, we can first find the middle vertex $v$ by performing for example dfs from $t$ and after finding it, compute the maximum distance from v into any vertex in v’s subtree where also $j$ is located, which can be also done using dfs.

Subtask 2

In this subtask, in each query, node $j$ is fixed. This allows us to precompute for all nodes $u$ the middle node on path from $j$ to $u$ using a single dfs from $j$ beforehand. Moreover, for each node $u$, the longest path from $u$ descending into its subtree where $j$ is also located can be computed similarly also beforehand. This allows us to answer each possible query offline using these precomputed informations.

Subtask 3

In this subtask, in each query, node $t$ is fixed, so the problem is very similar to the one in the second subtask and the approach follows also the same idea, but has to be implemented independently of the solution for the second subtask, because slightly different informations have to be precomputed.

Subtask 4

In this subtask we know that $N \leq 5000$ and besides that all original constraints are preserved. At least a few possible approaches can take advantage of this fact and one of them is to first compute middle nodes for all possible pairs of nodes $t$ and $j$, which can be computed for example by using dfs from each possible node $t$ in order to compute middle nodes from $t$ to all other nodes, and then use dynamic programming to compute $dp[v][u]$ as the length of the longest path starting from $v$ and descending into subtree of $v$ where $u$ is located. Then, all queries can be answered offline by using both these look-up tables to locate the middle node first, and then computing longest paths from this middle node descending into subtree where $j$ is located. The total time complexity of this method is $(N^2 + Q)$ for a single test case.

Subtask 5

In the last subtask, we can have up to $10^5$ nodes and queries, which makes the problem significantly harder than it is in any of the earlier subtasks. However, remember that the same general rule for solving the problem applies, and it just has to be implemented more efficiently. Just to recall, the strategy is to solve each query $(t, j)$ independently, by first finding the middle node $v$ in the path from $t$ to $j$ and then compute the most distant node from $v$ located in the same subtree of $v$ that $j$ is located in.

The first part, finding the middle node, can be solved using LCA algorithm. The idea is that finding $L = LCA(t, j)$ allows us to find the length of the path between $t$ and $j$, which can be used to find the middle node when it’s combine with the function $getKthAncestor(u,k)$ returning the $k$-th ancestor of $u$. This function can be implemented using, so-called jumps table which is also used to compute LCA of two nodes. For implementation details please refer to setter and both testers solutions listed below, or this TopCoder article on how to compute LCA efficiently.

The second part, i.e. the maximum distance from $v$ to any node located in the same subtree of $v$ that $j$ is also located can be computed in a several ways. One possibility is to use to precompute for each edge $(v, u)$ in the tree, the maximum distance from $v$ to its subtree rooted in $u$. This can be easily done by running dfs with memoization. Notice that there are at most $2 \cdot N$ possible edges, resulting in the same number of entries in a look-up table they produce. This look-up table can be used to compute the final result as soon as the middle node is found. Exactly this approach was used by one of the testers for the problem. For other implementations you please refer to setter and second tester solutions listed below.

In summary, a single test case for this subtask can be solved in $O(N \cdot \log(N) + Q \cdot \log(N))$ time, and it is dominated by the time needed to compute LCA.

AUTHOR'S AND TESTER'S SOLUTIONS:


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

Why Am I getting WA??

$
0
0

Question: https://www.codechef.com/problems/CPERM

My Solution: https://www.codechef.com/viewsolution/12147288

I know that the solution to this problem is (2^(N-1) - 2) and I also know that the efficient way to find powers of 2 is by bitwise shift operator but I don't know y i am getting WA.

Here is the code:

#include <iostream>
using namespace std;

int main() {
// your code goes here
int T,N;
cin>>T;
while(T--)
{
    cin>>N;
    long long int ans = (1<<(N-1))-2;
    cout<<ans<<"\n";
 }
 return 0;
   }

Please can anyone find the mistake in my code.

CHEFSSET - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Praveen Dhinwa
Tester:Animesh Fatehpuria
Editorialist:Pawel Kacprzak

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Number theory, primes, fundamental theorem of arithmetic

PROBLEM:

For a given array $A[1..N]$ of $N$ integers, the goal is to use the minimal number of operations of multiplying some of these integers by any prime numbers, in such a way that after all these multiplications are performed, then for each two possible different elements of the array $A[i]$ and $A[j]$, the value of $A[i] \cdot A[j]$ is a square number.

QUICK EXPLANATION:

Use fundamental theorem of arithmetic to observe that a number $K$ is a square if and only if each prime number than occurs in the unique factorization of $K$ occurs there even number of times. Use this fact to determine the minimum number of operations needed to compute the final result.

EXPLANATION:

First, notice that $K$ is a square number if all of its prime divisors divides $K$ even number of times. This is the crucial fact to come up with the solution of the problem.

For now let’s assume that all input numbers are primes, which corresponds to what we have in the first and the second subtask. As we will see, this assumptions helps a lot with approaching the problem. Later, we will get rid of this limitation, and the resulting solution will be the exact method used in other subtasks.

Let’s pick any element of the array. Let’s assume it is $A[i]$ and that $A[i] = p$, where $p$ is some prime number. The question is what is the minimum number of times $p$ has to be multiplied by some primes in order to be sure that when it is multiplied with any other number (remember, we have primes only) from the array, the result is a square number?

Since $p$ is prime, it has only one prime in its factorization and it is exactly $p$. Moreover, it occurs there odd number of times, so in order to make $A[i] \cdot A[j]$ a square number, where $A[j] \neq p$, then at least $A[i]$ or $A[j]$ has to be multiplied at least once by $p$, to make the factor of $p$ appearing even number of times in the product. This fact applies to all $A[j] \neq p$, so in order to make all products $A[i] \cdot A[j]$ to be square numbers for all $A[j] \neq p$, then either $A[i]$ has to be multiplied at least once by $p$ or each such $A[j]$ has to be multiplied by $p$.

Here comes the next crucial observation. If we consider $S$ to be a set of all elements of array $A$ with the value $p$, then first of all, each element of $S$ should be multiplied by the same primes, because if one method minimizes the number of multiplications needed for one element with value $p$ then it can be applied to all elements with value $p$ and it will be optimal for all of them. Thus, all elements in $S$ will be multiplied by the same primes, so their final value will be the same. This implies that a product of any two elements of $S$ after the multiplications are done is a square number. Moreover, since we noticed that in order to make the product of $A[i] \cdot A[j]$, where $A[i] \in S$ and $A[j] \not\in S$ a square number, we either have to multiply $A[i]$ once by $p$ or all $A[j]$ once by $p$, so if we consider all elements of $S$ at once, then either we multiply each of them by $p$ once or multiply each element not in $S$ by $p$ also once in order to make $p$ a factor occurring even number of times in any of products we consider.

Based on the above observation we can came up with the following approach. Let’s consider all unique primes in the input. Moreover, let $c_p$ be the number of times that $p$ occurs in the input. Then in order to make all products in which exactly one of the elements has initial value $p$ a square numbers, we have to use $\min(c_p, N - c_p)$ multiplications by $p$.

Subtasks 1 and 2

Solutions to the first two subtasks are the exact implementation of the method described above.

Subtasks 3 and 4

Solutions to the last two subtask are follow ups to the method described above. Just to recall, in these subtasks there can be numbers in the input array that are not prime. However, it turns out that the solution for in this case is very similar to the one described above.

Let’s consider a prime number $p$ occurring odd number of times as a factor of exactly $c_p$ elements of the input array. Then in order to fix the all the products of pairs of elements of $A$, where exactly one of elements of each such pair has $p$ occurring odd number of times as its factor, we have to multiply either all such $c_p$ elements by $p$ or all $N - c_p$ other elements by $p$, and the minimum value of these two leads to the optimal solution. So the only thing to do is to first compute the list of all primes below $10^6$, which can be done using for example the Sieve of Eratosthenes, and then for each of these primes, accumulate the number of input elements that are divisible by such a prime an odd number of times. For implementation details please refer especially to setter’s solution listed below which exactly matches the method used here.

AUTHOR'S AND TESTER'S SOLUTIONS:


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

Computing Olympiad Problem Doubt!

$
0
0

I am a grade 12 student from Mumbai. I am planning to appear for the Zonal Computing Olympiad this Saturday which is for school students. I am facing a problem regarding a particular question from ZCO 2012. There is a test page where users can submit the solution and receive the results. I have submitted my solution however it says that the answer is wrong. It says that the program compiled successfully without any errors or warnings. The problem gives the right answer on my machine for the given example. I provide the question and my code below:

Question:

Zonal Computing Olympiad 2012, 26 Nov 2011 10:00 am-1:00 pm IST Problem 1 : Matched Brackets

A sequence of opening and closing brackets is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense. For instance, the sequences (), (()) and ()(()) are well-bracketed, while (, ()), (()(), and )( are not well-bracketed.

The nesting depth of a well-bracketed sequence tells us the maximum number of levels of inner matched brackets enclosed within outer matched brackets. For instance, the nesting depth of () and ()()() is 1, the nesting depth of (()) and ()(()) is 2, the nesting depth of ((())) is 3, and so on.

Given a well-bracketed sequence, we are interested in computing the following:

The nesting depth, and the first position where it occurs-this will be

the position of the first opening bracket at this nesting depth, where the positions are numbered starting with 1.

The maximum number of symbols between any pair of matched brackets,

including both the outer brackets, and the first position where this occurs-that is, the position of the first opening bracket of this segment.

For instance, the nesting depth of ()(())()(()())(()()) is 2 and the first position where this occurs is 4. The opening bracket at position 10 is also at nesting depth 2 but we have to report the first position where this occurs, which is 4.

In this sequence, the maximum number of symbols between a pair of matched bracket is 6, starting at position 9. There is another such sequence of length 6 starting at position 15, but this is not the first such position. Input format

The input consists of two lines. The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket ( and 2 denotes a closing bracket ). Nothing other than 1 or 2 appears in the second line of input and the corresponding expression is guaranteed to be well-bracketed. Output format

Your program should print 4 space-separated integers in a line, denoting the four quantities asked for in the following order: nesting depth, first position that achieves the nesting depth, length of the maximum sequence between matching brackets and the first position where such a maximum length sequence occurs. Testdata

You may assume that 2 ? N ? 105. In 30% of the test cases, 2 ? N ? 103. Sample Input

20 1 2 1 1 2 2 1 2 1 1 2 1 2 2 1 1 2 1 2 2

Sample Output

2 4 6 9

Time and memory limits

The time limit for this task is 1 second. The memory limit is 32MB.

My submitted solution is:

#include "iostream"
#include<stdio.h>
using namespace std;

int main()
{
    unsigned int i,n,o,c,dep,pos_d,pos_m,last_pos,max;
    char* arr,*rn;
    cin>>n;
    fflush(stdin);
    arr = new char [2*n];
    rn = fgets(arr, (2*n), stdin);
    c=o=dep=pos_d=pos_m=last_pos=max=0;
    for(i=0;arr[i];i++)
    {
        if(arr[i]==' ')
            continue;

        else if(arr[i]=='1')
        {
            o++;
            if(c>0)
                c--;
            else
            {
                dep++;
                pos_d = (i/2)+1;
            }
        }

        else if(arr[i]=='2')
        {
            c++;
            if(o>0)
                o--;
            if(o==0)
            {
                if(((i-last_pos+2)/2)>max)
                {
                    max=(i-last_pos+2)/2;
                    pos_m = 1+(last_pos+1)/2;
                }
                last_pos = i+1;
            }
        }
    }
    cout<<dep<<" "<<pos_d<<" "<<max<<" "<<pos_m;
    return 0;
}

Kindly help me find the problem as I don't see any error and I seem to be getting the right answer for the given example.

Some useful links:

ZCO 2012 Question paper: http://www.iarcs.org.in/inoi/2012/zco2012/zco2012-1a.php Test server site: http://www.iarcs.org.in/zco2013/index.php


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?

Help in: Hackerearth November Circuits: Fredo is in Hurry

$
0
0

Since the contest is over, I am asking it now. Here's the link to the question: Fredo is in a Hurry

And here's my implementation: link

The above code gets successfully compiled and passes the custom test cases on the compiler provided by hackerearth but when I submit the same, not a single test case is passed. I want to know the logic behind this problem.

Check 25! is divisible by 9317?

$
0
0

How to check 25! is divisible by 9317?

Why do I get a SIGSEGV?

$
0
0

Why I am getting a runtime error SIGSEGV in the problem? Where I am going wrong?

How to Get Internship at Codechef?

$
0
0

I want to know how to get internship at codechef.

Given A, B and C. How to find the value of (A^B)%C.

$
0
0

I try many times but failed. input : A B C are 12345 123456789 123456789012345 repectively. Output : 59212459031520 Please help me to solve this.

best way to check if a point lies inside a triangle or not

$
0
0

Given the coordinates of 3 vertices of a triangle and a point. What is the most accurate and efficient way to determine if the given point is inside the triangle?


Getting started here, questions about strategy, etiquitte, etc.

$
0
0

Hi guys.

I've just started here, I have a few questions about how I approach this place. Firstly, let me just say that wow - some of the problems here are pretty difficult, even for easy!

Alright, so I've just bunch of the questions in the FAQ, here's a few more.

  1. What's the etiquette for posting here? For example are 'I'm working XYZ practice problem, I've got TLE error, here's my code, what should I do?' questions ok?

  2. What's the general strategy for solving problem, or doing time optimization? Are there any tools that you use? Like, one of the things I can see that would be problematic, is when you get a 'wrong answer' but you don't know what the 'expected vs output' is. Is this just something you need to deal with as a programmer, to think of the corner cases yourself?

  3. Is there any way to get additional test data?

  4. How do you organise your code chef files in your IDE? For example, your class name (in Java) must called Main, and it can't be part of any package, when you paste in to the submitter, otherwise it'll give you an error, wondering how people deal with that.

  5. code reusablity - I get the feeling that a lot of this is going to be using various appropriate algorithms. What I would tend to do is import the package that contains the algorithm. But given that the submission has to be a single file with no non-native imports, is the only thing you can do, is copy the code in for each algorithm?

  6. Where would you start in terms of first problems to solve? For example I would suggest doing the Enormous Input test as one of your first problems.

.

codechef should include graph for lunchtime

$
0
0

I think there should be a graph for lunchtime.
so that participant can check there progress.

Programming tutorials/guide blog for beginners

Solution for Bookshelves problem of ZCO 2016

$
0
0

I was solving the Bookshelves problem of ZCO 2016 but got WA in 5 out of 15 test cases. Problem link

Problem statement-

Uncle Shiva is an avid collector of books. In his study he has two long shelves with N books in each of them. He has invited the artist Lavanya to decorate his study.
Lavanya feels that the arrangement of books in the two shelves is not aesthetic. She has come up with a measure for the elegance of the two shelves called Skew. The Skew of the two bookshelves is defined to be the sum of the heights of the tallest books in each of the two shelves.

Lavanya recommends rearranging the books between the two shelves so that the Skew is as small as possible. On the other hand, Uncle Shiva prides himself as a balanced personality and always wants the two shelves to have an equal number of books, N in each.

Lavanya is an artist, she merely recommends what needs to be done, leaving the actual rearranging to Uncle Shiva. Uncle Shiva on the other hand is lazy and would like to do very little work. As a compromise, Uncle Shiva is willing to exchange books between the two shelves K times and would like to do these exchanges cleverly so as to make the Skew as small as possible (via K swaps).

For example, suppose each shelf contained 5 books, where the heights of the books on the first shelf are 3, 5, 2, 7 and 1, and the heights of the books on the second shelf are 14, 2, 3, 10 and 4. The Skew of this arrangement is 7 + 14 = 21. If K = 1, i.e., Uncle Shiva is willing to exchange only one book between the two, he can swap the book with height 2 in shelf 1 with the book with height 14 in shelf 2 and this will increase the Skew to 24! On the other hand if he swaps the book with height 7 in the first shelf with the book with height 3 in the second shelf then the resulting arrangement has a Skew of 5 + 14 = 19. You can verify that if K = 1 then this is the smallest Skew that can be achieved. So for this case the answer is 19.

Your task is to write a program that takes as input, N - the number of books in each shelf, K - the number of swaps that Uncle Shiva is willing to do, and the heights of the books on the two shelves, and computes the smallest Skew value that can be achieved through at most K swaps of books between the two shelves.
Input format

There is only one line, which contains ((2 × N) + 2) space separated integers.
The first two integers are N and K.
The next N integers, give the heights of the N books in the first book shelf.
The last N integers, give the heights of the N books in the second book shelf.
Output format

A single line with a single integer giving the minimum Skew that can be achieved via at most K swaps between the two bookshelves
Test data

You may assume that the height of all the books like in the range between 0 and 108, both inclusive and that 1 ≤ N ≤ 105. Note that there may be more than one book with the same height on a bookshelf.

Subtask 1 (30 Marks) You may assume that K = 1.
Subtask 2 (70 Marks) 0 ≤ K ≤ N.

Sample Input

5 1 3 5 2 7 1 14 2 3 10 4
Sample Output
19

Below is my code in JAVA. I am getting WA in task #5,11,12,14,15. Since, I am getting AC in some test cases means I am just missing something in my code. Code submission and result.

import java.util.*;
class ZCO16001
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int a[]=new int[n];
        int b[]=new int[n];
        for(int i=0;i<n;i++)
        {
            a[i]=sc.nextInt();
        }
        for(int i=0;i<n;i++)
        {
           b[i]=sc.nextInt();
        }
        Arrays.sort(a);
        Arrays.sort(b);
        int flag=1;
        for(int i=0;i<k;i++)
        {
            if(flag==0)
            {
                break;
            }
            int m=n;
            int p=0;
            do{
            if(a[m-1]>b[m-1])
            {
                if(b[m-1]>a[0])
                {
                    int temp= a[0];
                    a[0]=b[m-1];
                    b[m-1]=temp;
                    Arrays.sort(a);
                    Arrays.sort(b);
                    break;
                }
                else
                {
                    flag=0;
                    break;
                }
            }
            if(a[m-1]<b[m-1])
            {
                if(a[m-1]>b[0])
                {
                    int temp= b[0];
                    b[0]=a[m-1];
                    a[m-1]=temp;
                    Arrays.sort(a);
                    Arrays.sort(b);
                    break;
                }
                else
                {
                    flag=0;
                    break;
                }
            }
            else
            {
               m--;
            }
            }while(m!=2);
    }
    System.out.println(a[n-1]+b[n-1]);
}
}

Please help me out.

Solution for Matched Brackets problem of ZCO 2012

$
0
0

Hey, I was solving this question using JAVA, but I got a WA in the second last test case of the first sub-task and the last test case of the second sub task. Rest all 13 test cases were AC. Can someone look at my code, I have literally been scratching my head for two hours.

Problem page: https://www.codechef.com/ZCOPRAC/problems/ZCO12001

Code submission and test result: https://www.codechef.com/viewsolution/12146831

Problem Statement -

A sequence of opening and closing brackets is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense. For instance, the sequences (), (()) and ()(()) are well-bracketed, while (, ()), (()(), and )( are not well-bracketed.


The nesting depth of a well-bracketed sequence tells us the maximum number of levels of inner matched brackets enclosed within outer matched brackets. For instance, the nesting depth of () and ()()() is 1, the nesting depth of (()) and ()(()) is 2, the nesting depth of ((())) is 3, and so on.


Given a well-bracketed sequence, we are interested in computing the following:

The nesting depth, and the first position where it occurs–this will be the position of the first opening bracket at this nesting depth, where the positions are numbered starting with 1.

The maximum number of symbols between any pair of matched brackets, including both the outer brackets, and the first position where this occurs–that is, the position of the first opening bracket of this segment


For instance, the nesting depth of ()(())()(()())(()()) is 2 and the first position where this occurs is 4. The opening bracket at position 10 is also at nesting depth 2 but we have to report the first position where this occurs, which is 4.


In this sequence, the maximum number of symbols between a pair of matched bracket is 6, starting at position 9. There is another such sequence of length 6 starting at position 15, but this is not the first such position.


Input format

The input consists of two lines. The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket ( and 2 denotes a closing bracket ). Nothing other than 1 or 2 appears in the second line of input and the corresponding expression is guaranteed to be well-bracketed.


Output format

Your program should print 4 space-separated integers in a line, denoting the four quantities asked for in the following order: nesting depth, first position that achieves the nesting depth, length of the maximum sequence between matching brackets and the first position where such a maximum length sequence occurs.


Testdata

You may assume that 2 ≤ N ≤ 105. In 30% of the test cases, 2 ≤ N ≤ 103.
Subtask 1 (30 marks)
Subtask 2 (70 marks)

Sample Input

20
1 2 1 1 2 2 1 2 1 1 2 1 2 2 1 1 2 1 2 2

Sample Output

2 4 6 9

My code in JAVA -

import java.util.*;
class ZCO12001
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int a[]=new int[n];
        for(int i=0;i<n;i++)
        {
            a[i]=sc.nextInt();
        }
        int c1=0;
        int c2=0;
        int s1=0;
        int s2=0;
        int h=0;
        int i=0;
        do
        {
            int c2x=0;
            int s2x=0;
            if(a[i]==1)
            {
               h++;
               i++;
               c2x=1;
               s2x=i;
               while(h>0)
               {
                   if(a[i]==1)
                   {
                       h++;
                       i++;
                    }
                    else
                    {
                        h--;
                        i++;
                    }
                   if(c1<h)
                    {
                        c1=h;
                        s1=i;
                    }
                   c2x++;
               }
            }
            else
            {
                i++;
            }
            if(c2x>c2)
            {
                c2=c2x;
                s2=s2x;
            }
        }while(i<n);
        System.out.println(c1+" "+s1+" "+c2+" "+s2);
    }
}
Viewing all 39796 articles
Browse latest View live


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