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

NOKIA - Editorial

$
0
0

PROBLEM LINKS:

Practice
Contest

DIFFICULTY

Simple

PREREQUISITES

arrays, divide-and-conquer, recursion

PROBLEM

Given an array A[0..N+1], consider the indices [1..N] as spots for the soldiers and index 0 as the left tower and the index N+1 as the right tower. Initially set A[0] = 1, A[N+1] = 1 and rest all have 0s. Given a permutation P[1..N] of the indices {1, 2,...,N}, we fill them with 1s in that order and find the length of used wire as follows.

used_length = 0 for i = 1 to N used_length += ( distance from index P[i] to nearest index having 1 to left ); used_length += ( distance from index P[i] to nearest index having 1 to right ); A[ P[i] ] = 1;

You can see that the used_length depends on the permutation P and given an integer M, we need to find the minimum length of unused wire. It is same as asking for the maximum possible used_length≤ M for some permutation P. If M is not sufficient for any permutation P, output -1.

QUICK EXPLANATION

If you have solved the problem or almost got it yourself, this explanation is for you. If you have not solved it and eager to know how to build the idea from scratch, skip this part and go to the Detailed explanation section below.

There is a simple bruteforce solution and other clever solution. They are explained below.

  1. N = 30 is so small that you can generate all possible used_lengths for each N = 1 to 30. For a given N, we just need to fix the first position and that partitions the problem in to two independent smaller subproblems and we can merge the answers to these smaller subproblems. If we consider the number of possible used_lengths for a given N to be of order O(N2), this requires time O(N5), which is fast enough for N = 30.

  2. Given N, we can find the minimum and maximum used_lengths.

For minimum, its always better to try partitioning the problem into two equal subproblems.
minLen[n] = (n+1) + minLen[n/2] + minLen[n-1-n/2]

For maximum, we just need to place in the order {1,2,3...N}
maxLen[n] = (n+1) + maxLen[n-1] , this is same as maxLen[n] = (n*(n+3))/2

Now, can you prove that all the values between [ minLen[n], maxLen[n] ] are possible ? An idea is given in tester's approach.

DETAILED EXPLANATION

If you haven't solved this problem yet, take some time now and try different cases on paper. eg. Consider N = 4 and try to find all possible sum_of_lengths for different permutations of {1,2,3,4}. You can also take a look at the explanation of sample cases under the problem statement for better understanding.

First lets see an almost bruteforce solution. Consider the array A for N = 9.
Initially A = |, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
and we need to fill the array with 1s in some order. Suppose if we set A[4] = 1,
then A = |, 0, 0, 0, 1, 0, 0, 0, 0, 0, |
and length of wire on left side = 4, length of wire on right side = 6, so we need wire of length 4 + 6 = 10.

Note that if we place the first soldier among N spots at any index, we need wire of length (N+1). Not only that, the first soldier now acts as a barrier between his left and right sides. There will never be a wire which cross this soldier. So we have two independent problems now. If the first solder is placed at index I, then we need (N+1) length wire for this soldier and solve subproblem with (I-1) spots on left side and subproblem with (N-I) spots on right side.
A = |, 0, 0, 0, 1, 0, 0, 0, 0, 0, | is same as solving
A = |, 0, 0, 0, | and |, 0, 0, 0, 0, 0, |

So we can store all possible values for each N = 1 to 30, and for a given N try all possible positions for the first soldier and mix the answers of the two independent subproblems to get all possible values. As the constraint on N is 30, you can just bruteforce each of these steps.

For an alternate simple approach, see point 2 in the quick explanation section.

SETTER'S SOLUTION

Can be found here

APPROACH

The problem setter used the approach given in the detailed explanation above.

TESTER'S SOLUTION

Can be found here

APPROACH

The problem setter and the tester have independently observed that each of the values between [min, max] can be achieved for some permutation P. This method takes only O(N) time. Here is a rough idea of the proof using induction, in tester's words.

max[0] = min[0] = 0
max[n] = max[n-1] + n+1
min[n] = min[n/2] + min[n - n/2 - 1] + n+1
Therefore max[n] = n * (n+3) / 2, min[n] = O(n log n).

Here we assume that for k = 1,2,...,n-1, [ min[k], max[k] ] are all possible,
then we should prove [ min[n], max[n] ] are all possible.
From min[n/2] + min[n - n/2 - 1] + n+1 to max[n/2] + max[n - n/2 - 1] + n+1 are all possible by the assumption.
If min[a+1]+min[n-a-2] ≤ max[a]+max[n-a-1] for all a=n/2, n/2+1, ..., n-2, then we can show [ min[n], max[n] ] are all possible.
L.H.S. = O(n log n), R.H.S = O(n^2), therefore, this is correct for large n.

If you can come with a more intuitive and simple proof, please edit this post and add a section 'Alternate Proof'.


Discrepancies in Codechef Rating

$
0
0

Dicrepancy

Hello All, My codechef rating after last cook off was 1976 until I checked today afternoon. Suddenly it displays a discrepancy of 1975(-1). May I know the reason why?

FRUITS - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Sunny Aggarwal
Tester:Vasya Antoniuk
Editorialist:Pushkar Mishra

DIFFICULTY:

Cakewalk

PREREQUISITES:

Ad-hoc

PROBLEM:

Given are the number of apples ($N$) and oranges($M$) and $k$, i.e., the amount of money that chef has to buy apples/oranges. Each orange/apple costs 1 unit. What is the minimum difference that can be achieved.

EXPLANATION:

The problem is a very direct one. We have to minimize the difference. We can only increase the number of apples or oranges that we have. The logical step is to increase that commodity which is less because increasing the which is already more will only increase the the difference. Let $minC$ denote the quantity which is less. Let $maxC$ be the quantity which is more. The answer is given by:

$ans = maxC - min(minC+k, maxC)$

We have a min operation in the second term because the optimal case is to make both the quantities equal. If we have enough money to increase the lesser one to more than the other one, then we would rather make them equal so as to have a difference of zero, which is optimal.

COMPLEXITY:

$\mathcal{O}(1)$ per test case.

SAMPLE SOLUTIONS:

Author
Tester
Editorialist

What's wrong with my code : The Lead Game - TLG (Beginner level)

$
0
0

#include<iostream>
using namespace std;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    cin>>n;
    int a,b;
    int dif[2]={0};
    for(int i=0;i<n;i++) {="" cin="">>a>>b;
        if(a>b && (a-b)>dif[1])
        {
            dif[1]=a-b;
            dif[0]=1;
        }
        else if(b-a>dif[1])
        {
            dif[1]=b-a;
            dif[0]=2;
        }
    }
    cout<<dif[0]<<" "<<dif[1]<<endl;="" }="" <="" code="">

TSECAU01 - Editorial

$
0
0

Problem Link:

Practice

Contest

Author:tseccodecell

DIFFICULTY:

Cakewalk

PREREQUISITES:

Addition

PROBLEM:

Find sum of two numbers.

QUICK EXPLANATION:

$C=A+B$.

EXPLANATION:

Total of number of fruits and oranges can be found using addition. The problem is meant to be an introduction to people who haven't used the codechef platform before.

SOLUTION:

https://ideone.com/wNIJ6z

TSECAU02 - Editorial

$
0
0

Problem Link:

Practice

Contest

Author:tseccodecell

DIFFICULTY:

Cakewalk

PREREQUISITES:

Simple arithmetic operations

PROBLEM:

Given circumference of two wheels $X$ and $Y$, and the difference is distance travelled by them $D$ for the same number of revolutions, find the number of revolutions.

QUICK EXPLANATION:

Use the formula $R=(D / abs(X-Y))$ where abs is absolute value or modulus.

EXPLANATION:

Let distance travelled by wheel A and B be D1 and D2 respectively. Then D1=XR and D2=YR. But we know that positive difference of D1 and D2 is D.

Therefore,

D=abs(D1-D2)

D=abs(X*R-Y*R)

D=R*abs(X-Y)

R=D/abs(X-Y)

SOLUTION:

https://ideone.com/lfmXHp

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.

.

CIELRCPT - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

DIFFICULTY

CAKEWALK

PREREQUISITES

Greedy Algorithms

PROBLEM

You need to find the representation of a given integer N as a sum of powers of two up to 211 with the smallest number of summands (repetitions in representation are allowed).

QUICK EXPLANATION

The problem can be solved by greedy algorithm: at each step we should take the largest possible menu that we can. To prove this noticed that if we order two equal menus, say 4 and 4, then we can order instead one menu of cost 8. In this problem you can implement this approach in any way you like but the easiest and fastest way gives the following pseudo-code:

res = 0
for i = 11 to 0
  res = res + N div 2i
  N = N mod 2i

EXPLANATION

At first we reveal the answer and then will prove it in detail. Write N as Q * 2048 + R, where Q and R are non-negative integers and R < 2048. Then the answer is Q + bitCount(R), where bitCount(X) is the number of ones in binary representation of X. If R = 2h[1] + 2h[2] + ... + 2h[K] is a binary representation of R then the optimal representation of N is N = 2048 + ... + 2048 + 2h[1] + 2h[2] + ... + 2h[K] where we have Q copies of 2048. Let’s call this approach formula approach.

Another way to come up with this answer is to use Greedy Algorithm. That is, at each step you should take the largest possible summand among {1, 2, 4, 8, ..., 2048} that is not greater than the current value of N and then subtract it from N. In fact, this problem is a special case of Change-making problem and in general it should be solved using Dynamic Programming or Integer Linear Programming but this set of coin values is special and admit using of Greedy Algorithm as we will see below.

Now we discuss why both of these approaches are correct.


1. Formula Approach.

Let’s prove that formula approach is correct. Consider some representation of N as a sum of allowed powers of two. Let there is exactly C[K] occurrences of 2K in this representation. Then we have

N = C[0] * 1 + C[1] * 2 + C[2] * 4 + ... + C[11] * 2048

Note that the total number of summands here is C[0] + C[1] + ... + C[10] + C[11]. Assume that for some K < 11 we have C[K] >=2, that is, we have at least two copies of 2K in the representation of N. Since K < 11 then the price 2K+1 is allowed. Hence we can replace two copies of 2K by one copy of 2K+1 not changing the value of sum but decreasing total number of summands. Thus, for optimal representation we should have

C[K] <= 1 for all K < 11.                         (1)

We will show that under the constraints (1) representation of N is uniquely determined. Of course this unique representation will be the optimal one.

At first note that

R = C[0] * 1 + C[1] * 2 + C[2] * 4 + ... + C[10] * 1024 <= 1 + 2 + 4 + ... + 1024 = 2047 < 2048.

Hence

2048 * C[11] <= N < 2048 * (C[11] + 1)

or

C[11] <= N / 2048 < C[11] + 1

which means by one of the definition of floor function that C[11] = floor(N / 2048) = Q. So C[11] is uniquely determined under the constraints (1) and equals to Q.

Further note that due to (1) C[10]C[9]...C[1]C[0] is a binary representation of R and hence C[0], C[1], ..., C[10] are also uniquely determined under the constraints (1).

Thus we have found this unique representation.

Next we have bitCount(R) = C[0] + C[1] + ... + C[10]. Hence the total number of summands in this representation is Q + bitCount(R) as was announced earlier. The complexity of this method is O(K), where K = 12 is the total number of powers of two that we are allowed to use.


2. Greedy Approach.

Now let’s see why greedy approach produces the same solution. Clearly at first several steps we will take the 2048 until we get a number strictly less than 2048. Then we will consider powers of two in descending order starting from 1024 and take the current power of two if it is not greater than the current value of N. It is quite clear that this process generates exactly the binary representation of N. Thus the whole representation coincides with the constructed above.

There are several ways how to implement this algorithm in this problem. First one is simple but slower in general. Namely, we have an outer loop of the form while (N > 0). Then at each iteration of this loop we simply check in one loop all allowed powers of two in descending order until we find the power of two, say 2X, that is not greater than the current value of N. After that we decrease N by 2X and increase answer by 1. The complexity of this approach is O(N / 2K-1 + K2) in the worst test case. This is because at first N / 2K-1 steps we have only one iteration of inner loop (we break at 2048) and then we have at most K steps for each of which we have at most K steps in the inner loop.

In second method we swap outer and inner loop of the first method. So we iterate over allowed powers of two in descending order and for each power of two we have an inner loop of the form while (N >= 2X) in the body of which we do the same as for the first method, that is, decrease N by 2X and increase answer by 1. The complexity of this method is O(N / 2K-1 + K). Strictly speaking the number of basic operations in this method is O(answer + K). N / 2K-1 + K is an upper bound for the answer.

Analyzing second implementation of the greedy approach it is easy to see how to make it faster. For each power of two we have the following inner loop

while N >= 2X do
  N = N - 2X
  res = res + 1

Clearly this equivalent to

  res = res + N div 2X
  N = N mod 2X

Thus we obtain third implementation of the greedy algorithm with complexity O(K).


3. Dynamic Programming Approach.

Now let’s consider another approach that allows to find the answer for arbitrary set of coin values in reasonable time. We will use dynamic programming. Let d1, ..., dK be the set of allowed coin values (they all are positive). Denote by F(P) the minimal number of coins needed to represent P by this set of coins (repetitions in representation are allowed). Clearly F(0) = 0. Consider some value of P > 0. Then it is quite clear that

F(P) = min{F(P - d1), F(P - d2), ..., F(P - dK)} + 1.            (2)

where we set for convenience F(x) = INF for x < 0 (INF is some very large number). But let’s prove this formally.

At first consider the optimal representation for P. Let it be P = A1 + ... + AL where L = F(P) and each Ai is of course equal to one of dj. Then A2 + ... + AL is some representation of P – A1 of the length L – 1. By definition of F(P – A1) we have
L – 1 >= F(P – A1)
or
F(P) >= F(P – A1) + 1.
Since A1 is equal to one of dj then
F(P – A1) >= min{F(P - d1), F(P - d2), ..., F(P - dK)}.
Combining the last two inequalities we get the first part of (1). Namely

F(P) >= min{F(P - d1), F(P - d2), ..., F(P - dK)} + 1.            (3)

Now let dj be those coin value for which F(P - dj) is minimal among F(P - d1), F(P - d2), ..., F(P - dK). Let B1, ..., BZ be the optimal representation for P - dj. That is P - dj = B1 + ... + BZ and Z = F(P – dj). But then P = dj + B1 + ... + BZ. So P has a representation of the length Z + 1 which by definition of F(P) means that

F(P) <= Z + 1 = F(P – dj) + 1 = min{F(P - d1), F(P - d2), ..., F(P - dK)} + 1.            (4)

Now (2) follows from (3) and (4). Formula (2) allows to find all values F(0), F(1), ..., F(N) in a simple double loop. So F(N) can be found in O(N * K) time with O(N + K) memory.

SETTER'S SOLUTION

Can be found here.
Setter used the third implementation of the greedy approach described above.

TESTER'S SOLUTION

Can be found here.
Tester solution has complexity O(log N) (if we replace i <= 17 by 2i<= h). In this solution he implicitly deals with more natural version of the problem where all powers of two are allowed, that is, we simply need to find bitCount(h). To get the correct answer he increase answer by 2i-11 instead of 1 for each power of two that is greater than 211 and presented in the binary expansion of h.

RELATED PROBLEMS

Greedy Change (Codeforces Beta Round #10, problem E)
Let Me Count The Ways (UVA 357)


TSECAU03 - Editorial

$
0
0

PROBLEM LINK:

PracticeContest

Author:tseccodell

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Graphs,connected components, dfs, bfs

PROBLEM:

Find minimum number of Zakos to be paid such that their sum is minimum. Find all those Zakos with maximum friends.

QUICK EXPLANATION:

Run DFS/BFS multiple times to find the minimum sum in every connected component.

EXPLANATION:

In this problem you are given an undirected graph with weighted vertices. Store the pair of weight of the vertex and its position in a vector V. Then create adjacency representation for all edges. Sort the vector V,in non-decreasing order, so that we get vertex with minimum weights.Now for each connected component run DFS and simultaneously add the minimum weight vertex to final answer.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.

what is wrong in my question?It is working fine in all editor .Please help me

$
0
0

include<stdio.h>

include<string.h>

define m 3

int main() { int i,j,t,flag; char str1[m],str2[m];

scanf("%d",&t); while(t--) { scanf("%s",str1); scanf("%s",str2); if(((str1[0]=='o')||(str2[0]=='o')) && (((str1[1]=='b')||(str2[1]=='b')) && ((str1[2]=='b')||(str2[2]=='b')))) { flag=1; } else if(((str1[1]=='o')||(str2[1]=='o')) && (((str1[0]=='b')||(str2[0]=='b')) && ((str1[2]=='b')||(str2[2]=='b')))) {

            flag=1;
       }
   else if(((str1[2]=='0')||(str2[2]=='o')) && (((str1[0]=='b')||(str2[0]=='b'))&&((str1[1]=='b')||(str2[1]=='b'))))
        {
           flag=1;
        }
    else{
        flag=0;
    }
    if(flag==1)
      printf("yes\n");
    else
       printf("no\n");

} return 0; }

RUBBER - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Jineon Baek

Tester:Suchan Park

Editorialist:Jineon Baek

DIFFICULTY:

Very Hard

PREREQUISITES:

PROBLEM:

You are given a polyline and $n$ points. You can think the given polyline as a rubber band, so it can be stretched freely, but you are not allowed to cut into pieces. Is it possible to move the rubber band so that the band escape from all the points?

EXPLANATION:

First of all, let's assume that the positions of nails have different $x$ coordinates. This can be achieved by, say, rotating the whole plane by a small angle.

We can check if the rubber band can be separated by the following method: For the $i$'th nail from left, assign a ray $L_i$ directed upward from the nail. Now pick any point $p$ on the rubber band and move $p$ along it. Whenever the point $p$ passes $L_i$ from left to right, assign a number $i$, and whenever $p$ passes $L_i$ from right to left, assign a number $-i$. Call the final sequence we obtain by moving $p$ along the rubber band completely as $w$.

[Fig 1]: An example of 3 nails and a rubber band, with the sequence w = (something) assigned to the band.

The rubber band can be freed if and only if we can get an empty sequence by repeatedly remove two adjacent numbers of same absolute value and opposite sign. For example, the sequence 5 -2 2 4 1 3 3 -3 -3 -1 -4 -5 corresponds to a removable band, but the sequence 1 2 -1 -2 isn't. The algorithm can be implemented effectively by examining all possible intersections in order, and it takes $O(NM)$ time.

It remains to show why this method works. Note that we can first assume that the rubber is on the set $X$, which is the plane with the points corresponding to nails removed. The rubber band can be freed if and only if the rubber band can be moved inside the set $X$ and be condensed to a point. If this is possible, we say that the rubber is null-homotopic in $X$. We can deform $X$ into a collection of circles joined along a single common point as the following picture. Note that the rubber band deforms along too. Noe that this deformation process does not change the answer to the problem of whether the band is null-homotopic or not. This is something we call homotopy equivalence in mathematics.

[Fig 2]: A sequence of pictures deforming the plane with nails removed to a collection of circles joined along a single common point.

Each nail makes a hole, and thus corresponds to one circle in the final picture. By the way how we deformed X, we can see that the sequence we defined in previous paragraph tracks down the sequence of circles the rubber band wraps around: the absolute value of each number denotes the circle the rubber band wraps around, and the sign denotes the direction (clockerwise/counterclockerwise) of the rubber band. The fact that the rubber band is null-homotopic if and only if the sequence can be reduced to an empty sequence can be shown rigorously by the fact that the fundamental group of a wedge product of circles is a free group. Still, even without this mathematical fact, you can convince yourself that the method above will work by playing around with a couple examples.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

Invitation to CodeChef August Long Challenge 2018 sponsored by ShareChat!

$
0
0

Hello CodeChef Community!

We are thrilled to invite you to participate in the August Long Challenge 2018 sponsored by ShareChat. In addition, there are some exciting internship and full-time job opportunities by ShareChat for Indian programmers in the August Long Challenge 2018. For more details, you may visit the contest page. I hope you will join your fellow programmers and enjoy the contest problems. Joining me on the problem setting panel are:

Contest Details:

Time: 3rd August 2018 (1500 hrs) to 13th August 2018 (1500 hrs). (Indian Standard Time — +5:30 GMT) — Check your timezone.

Contest link:www.codechef.com/AUG18

Registration: You just need to have a CodeChef handle to participate. For all those, who are interested and do not have a CodeChef handle, are requested to register in order to participate.

CHO2 - Editorial

$
0
0

PROBLEM LINK:

(https://www.hackerrank.com/challenges/day-of-the-programmer/problem)

Contest

Author:Vaisshnavi Yerrapothu

Tester:Vaisshnavi Yerrapothu

DIFFICULTY:

CAKEWALK.

PREREQUISITES:

Strings, Arrays.

PROBLEM:

Given a year ,y , find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.

EXPLANATION:

As it is very easy question, the code snippet will guide you. ` def solve(year): if (year == 1918): return '26.09.1918' elif ((year <= 1917) & (year%4 == 0)) or ((year > 1918) & (year%400 == 0 or ((year%4 == 0) & (year%100 != 0)))): return '12.09.%s' %year else: return '13.09.%s' %year

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found [here] https://www.hackerrank.com/rest/contests/master/challenges/day-of-the-programmer/hackers/16wh1a05c01/download_solution

Can anyone post the editorial of MCQ game problem (T-24)from Innerve Summer of Code Challenge ?

$
0
0

I have gone through a lot of successful submissions for MCQ game problem but still not able to understand them ,specially why mod has been changed to mod-2.Please help.

CodeChef beginner - The Lead Game (TLG) whats wrong in my code?

$
0
0
#include "bits/stdc++.h"
using namespace std;

int main()
{
    int t, s1, s2, lead;
    cin >> t;
    vector<int>p1;
    vector<int>p2;
    while(t--)
    {
        cin >> s1 >> s2;
        if(s1> s2)
            {
                p1.push_back(s1-s2);
            }
        else
            {
                p2.push_back(s2-s1);
            }
    }
    int max1 = *max_element(p1.begin(),p1.end());
    int max2 = *max_element(p2.begin(),p2.end());
    if( max1 > max2)
        cout << "1 " << max1;
    else
        cout << "2 " << max2;
}

Error in rating shown on profile page.

$
0
0

Why does my profile show two different ratings, one in the graph and another above my stars?

(For those willing to hammer me with plagiarism, it's not the case here.)

@admin@vijju123

alt text

TSECAU04 - Editorial

$
0
0

Problem Link:

Practice

Contest

Author:tseccodecell

DIFFICULTY:

Easy

PREREQUISITES:

Level order traversal(BFS)

PROBLEM:

In a complete binary tree, find subtree with maximum level N which has maximum sum of elements.

QUICK EXPLANATION:

We can obtain the sum of sub-tree of the binary tree if we visit each node in the level order traversal or breadth first search.

EXPLANATION:

We can find the maximum sum sub-tree of maximum level n by traversing n-1 levels(or uptil last level of tree) of each node and finding their sum. Finally the the correct sub-tree is the one having maximum sum for level n.

We store the root node of the maximum sub-tree and finally print the sub-tree once again using level order traversal.

SOLUTION:

https://ideone.com/bUfMGS

T21 - Editorial

$
0
0

PROBLEM LINK:

[Contest] T21

Author:Nandishwar Garg

DIFFICULTY:

SIMPLE

PREREQUISITES:

None

PROBLEM:

You are given two large numbers m and n. You have to multiply m and n then product is needed to be divided by 3. What will be the remainder after division?

EXPLANATION:

To solve the problem, just go through these 3 steps:

Step 1: The given numbers m and n are needed to be multiplied.

Step 2: The product which you get after multiplying the numbers is needed to be divided by 3.

Step 3: Print the remainder you get.

AUTHOR'S SOLUTION:

Author's solution can be found here

T22 - Editorial

$
0
0

PROBLEM LINK:

[Contest] T22

Author:Nandishwar Garg

DIFFICULTY:

SIMPLE

PREREQUISITES:

Looping Knowledge

PROBLEM:

You are given array of size N. You have to find product of each ai and aj. Now you have to check whether ai*aj is smallest prime number or not? If it the smallest prime number exists then print it otherwise print -1.

EXPLANATION:

Suppose the size of array is 3 and the elements of array are 1, 2 and 3. You have to find the product (ai*aj) of elements. So, in this case product will be 2,3,6.

Now you need to find the prime numbers among the products. Here, the prime numbers are 2 and 3. Further you need to find the smallest number among the prime numbers. In this case, the smallest prime number is 2. So, you need to print 2.

We take another example, the size of array is 4 and elements are 5, 5, 5 and 2. Their products will be 25, 25, 10, 25,10,10. This product set doesn’t contain any prime number so you are required to print -1.

AUTHOR'S SOLUTION:

Author's solution can be found here

Ambiguous behaviour of getline() and cin.ignore() in C++

$
0
0

Hey! I want an explaination for this scenario : Solution 1

Solution 2

In soltion 1 , i'm taking no. of test cases as input through cin and then ignoring the remaining line by using cin.ignore(). This results in WA. While in Solution 2 , i'm taking the no.of test cases as input using getline and then converting it into int. This gives AC. Why is that so?? thanks in advance!

Viewing all 40121 articles
Browse latest View live


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