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

Very weak test cases for problem IEMCO5D

$
0
0

I want to report wrong constraints / incorrect test cases in wakeup sid question(IMECO5D). I have gone through accepted submissions of others and noticed that those who didn't assert the constraint 0 <= L + R <= N - 1, got their answers accepted. I ensured that constraint and got Wrong Answer.

I also found that many bruteforce solutions were accepted and some other solutions that didn't handle integer overflows were also accepted. But according to the given constraints, they should result in Time Limit Exceeded or Wrong Answers.

So either this question must be removed or all the submissions must be rejudged with proper testcases.


Problem LISA too strict time limit?

$
0
0

As the title says, for the problem LISA , the time limit seems to bee too strict which is has no AC solution yet.

@admin , could you please have a look and make the corrections if needed.

Invitation to Dementia '18 (Rated for Division 2) !

$
0
0

Hi all,

Programming club, Indian Institute of Technology, Mandi is hosting Dementia '18 as part of our cultural-cum-technical fest Exodia. The contest will take place on 12th April,2018 at 20:00 IST. The contest features 6 delectable problems of varying difficulty and you'll get 2.5 hours for solving them. The problemsetters and testers for the contest are me(@avi224) and Hitesh(@hitman_coder). The contest is rated for division II on codechef(below 1800 rating). However, division I can participate out of competition and be eligible for prizes. alt text

There are prizes worth Rs 5K(only for Indian participants).

Link to the contestCombined ranklist

C++14: cin vs scanf

$
0
0

Here is the problem statement.

this code with cin gives AC, whereas this code with scanf gives WA in C++14.

Why is this happening?

MO's algorithm uses?

$
0
0

Can someone list some main things which can be done using MO's algorirhm like

1)Number of distinct elements in [l,r]

2)Sum of all elements in [l,r]

Can anyone suggest more like these?

help in a codeforces greedy problem 957D Riverside Curio

Bug in RUNDIR of april cookoff 2018

$
0
0

Can anyone tell me what's the reason behind this problem.

I have two solution of this RUNDIR problem of april 2018 cookoff div1.

Both the solutions are same , its just that in one solution i am printing -1 as :

cout<<"-1\n";

and in another by :

double temp = -1;

printf("%0.6lf\n",temp);

but the problem is that first approach gives wrong answer but second coorect.

Here are the links:

Approach 1 : https://www.codechef.com/viewsolution/18341188

Approach 2 : https://www.codechef.com/viewsolution/18341948

CODECHEF RATING PREDICTOR

$
0
0

https://crp.databread.xyz/

Hi.

I have created a Codechef Rating Predictor with UI and options to filter it by Institution and Country and Username.

Simply go to https://crp.databread.xyz and find the list of running contests to choose from.

Also, you can open it directly from the Codechef Ranking page. Simply replace codechef.com/ with crp.databread.xyz?

For Example : If contest Link is : https://www.codechef.com/rankings/APRIL18A?filterBy=Institution%3DIndian%20Institute%20of%20Technology%20Delhi&order=asc&sortBy=rank

Then Predicted Ratings are present at : https://crp.databread.xyz?rankings/APRIL18A?filterBy=Institution%3DIndian%20Institute%20of%20Technology%20Delhi&order=asc&sortBy=rank

Kindly let me know if there are any bugs.

**Github Link : https://github.com/Shraeyas/Codechef-Rating-Predictor**

Hope you like it.

Thanks.

Happy Coding :)


Invitation to CodeChef April Cook-Off 2018 Sponsored By ShareChat

$
0
0

Hello Fellow Coders!

When it comes to programming, it’s always the more the merrier! With that, I would like to invite you to Chef’s contest lined up for you, the April Cook-Off 2018 sponsored by ShareChat. In addition, there are some exciting job/internship opportunities by ShareChat in the April Cook-Off 2018. For more details, you may visit the April Cook-Off contest page. I hope you will join your fellow programmers in solving yet another exciting set of challenges. Joining me on the problem setting panel are:

  • Problem Setter: alei (Alei Reyes)
  • Problem Tester and Problem Editorialist: triveni (Triveni Mahatha)
  • Problem Verifier: xellos0 (Jakub Safin)
  • Russian Translator: xcwgf666 (Sergey Kulik)
  • Mandarin Translator: huzecong (Hu Zecong)
  • Vietnamese Translator: VNOI Team

I hope you will enjoy solving them. Please give your feedback on the problem set in the comments below, after the contest.

Contest Details:

Time: 22nd April 2018 (2130 hrs) to 23rd April 2018 (0000 hrs). (Indian Standard Time — +5:30 GMT) — Check your timezone.

Contest link:https://www.codechef.com/COOK93

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.

Prizes: Top 10 performers in Global and Indian category will get CodeChef laddus, with which the winners can claim cool CodeChef goodies. Know more here: https://www.codechef.com/laddu. (For those who have not yet got their previous winning, please send an email to winners@codechef.com)

Good Luck!
Hope to see you participating!!
Happy Programming!!

WA for 'Spam Classification Using Neural Net'

RUNDIR - Editorial

$
0
0

Problem Link:

Practice

Contest

Setter: Alei Reyes

Tester: Triveni Mahatha

Editorialist: Triveni Mahatha


Difficulty:

EASY MEDIUM

Prerequisites:

Binary Search, Greedy

Problem:

N students are standing at distinct points in the X-axis. Every students will start running at t = 0. assign direction (left/right) to each of them such that the first time when any two students cross each other is as large as possible. Speed of every students is given.

Quick Explanation:

Do binary search on the time. Suppose at any step in the binary search, we are are trying to find whether it is possible to assign direction such that no students will cross before some time say t.

To check, whether it is possible to assign direction. We fix the direction of leftmost students towards left (without loss of generality). For every other student from left to right, we try to fix the direction to left itself if it crosses non of the students before time t. And move to next student.

If it is not possible, we try to fix the direction as right. If it is possible then move to next student.

If we are able to assign direction to each students in that manner then the answer is yes, otherwise it is not possible.

SOLUTION:

Setter

Tester

Time Complexity:

For required precision, iterating 100 steps in the binary search is enough. Let's say the number of steps be S.

$O(S N)$ per test case.

Space Complexity:

$O(N)$

BINIM - Editorial

$
0
0

Problem Link:

Practice

Contest

Setter: Alei Reyes

Tester: Triveni Mahatha

Editorialist: Triveni Mahatha


Difficulty:

Easy

Prerequisites:

Combinatorial Game, Greedy

Problem:

Dee and Dum play modified nim game on N stacks of stones. Each stone can be of two types - 0 or 1. Dee can remove stones from a stack whose topmost element is 0. And Dum can only remove from stack with 1 at the top. If both play optimally who will win?

Explanation:

Note that to win the game, every player will try to pick stones such that number of moves for him is as large as possible before the end of the game. And, number of moves for the other player is as little as possible. This way he can make the other player run out of moves and can win.

How to achieve that?

Consider Dee. He can pick stones from stacks with top element as 0. So in every step, he will have to remove at least one 0-stones. How about picking exactly one 0-stone in each step? This way we see that he will waste no stones which are useful to him. Also, he can try to waste some of the stones of the other player by removing all consecutive 1-stones just below the top 0-stone. This gives him multiple advantages.

First, he picks no more than one 0-stone. Second, after removal of those stones, the top stone in the stack is still 0-stone. This means in future moves he can use this stack. Third, he wastes some 1-stones which are useful for the other person.

Using this strategy, he can make sure that all stacks whose top element is 0-stone will be used only by Dee, similarly other stacks will be used by Dum.

How many total moves Dee can make? It is number of 0-stones in all the stacks with top stone as 0-stone. Call this number stoneCountDee . Similary, let's define stoneCountDum as number of 1-stones in the stacks with top element as 1-stone.

If Dee moves first, he can win iff stoneCountDee $>$ stoneCountDum.

If Dum moves first, he can win iff stoneCountDum $>$ stoneCountDee.

SOLUTION:

Setter

Tester

Time Complexity:

Let's denote S be total number of stones in all N stacks. Then, Time complexity is $O(S)$ per test case.

Space Complexity:

$O(S)$

CHEFGORO - Editorial

$
0
0

Problem Link:

Practice

Contest

Setter: Alei Reyes

Tester: Triveni Mahatha

Editorialist: Triveni Mahatha


Difficulty:

MEDIUM-HARD

Prerequisites:

Bitmask, Topology

Problem:

Given a topology over a set X, find accumulation points of some subset R of X.

Explanation:

The hands of Goro defines a topology. Formally a topology over a set X is a collection T of subsets of X called open sets, in which the following conditions are satisfied:

  • $\phi$ and X belongs to T
  • Any finite intersection of sets that belongs to T also belongs to T
  • Any union of sets that belongs to T also belongs to T

In our case, X = {1, ..., m}, a recipe is a subset R $\subset$ X, and Suzumo is finding the accumulation points of R.

Formally, p is an accumulation point of set S, iff for every open set G that contains p, (G - {p}) ∩ S $\neq \phi$.

Let's denote the set of accumulation points of set A by A'. It turns out that (AB)'=A' ∪ B'. This observation suggests to find the accumulation points of every unitary set, and then use the union operation to find the accumulation points of any arbitrary set!

Let's represent sets as bitmasks of length m, bit i will be 1 if element i belongs to the set or 0 otherwise. Now we can use bitwise operations instead of set operations.

j is not an accumulation point of the unitary set {i} iff there exists an open set that contains j but not i. In bitwise language, it means that there exists a bitmask with a one in position j, and a zero in position i.

Instead of finding the accumulation points, it is easier to find the points that are not accumulation points.

Let f[x] be the points that are not accumulation points of {x}. We can fill f by performing the following operation over every open set b: f[i] |= b, where i iterates over every bit turned off in b.

Notes:

  • i is not an accumulation point of {i}.
  • It is not necessary to generate all the possible intersections of open sets.
  • Since the number of elements is at most 100, we can use __int128_t in C++, other ways to represent the bitmasks are a pair of long longs or bitsets

SOLUTION:

Setter

Tester

Time Complexity:

Let's say c is a constant to represent bitwise operations of bitset size m. Then,

$O(N m c)$ pre-computation. And, $O(m c)$ per query to answer them.

Space Complexity:

$O(m c)$

PWNCHESS - Editorial

$
0
0

Problem Link:

Practice

Contest

Setter: Alei Reyes

Tester: Triveni Mahatha

Editorialist: Triveni Mahatha


Difficulty:

MEDIUM

Prerequisites:

Basic understanding of combinatorial game theory is helpful but not necessary.

Problem:

Given a 1 x N length chess board and few white and black pawns placed on it. All white pawns are initially left of all black pawns. White can only move right and black can only move left. In each move only one pawn moves exactly one step. If both players plays optimally determine the winner (white plays first).

Explanation:

Let L and R be the columns of the rightmost white pawn, and the leftmost black pawn respectively. Let's call these two pieces "central pawns". There are two cases:

  • There is at least one cell between L and R.

The optimal game in this case is to keep moving the central pawns until there is exactly one cell between them (let's call this cell C the "center" ). Then both players can move any of their non-central pawns, until one of player is forced to move his central pawn and fall in a chain of captures, leading inevitably to the defeat.

Note that according to this strategy, Whites and Blacks try to place their pieces side by side at the left and right of the center.

Let's denote by SW the sum of distances of the white pawns to their target position (not occupied, nearest cell to the center). And by SB the corresponding sum of distances for Blacks.

White wins iff SW is strictly greater than SB. This is because once Whites place his central pawn one unit to the left of the center, he can wait as long as necessary forcing Blacks to move his central pawn to the center. Then Whites capture, rinse and repeat. Similarly by a symmetric argument can be proved that this condition is sufficient.

   L  C  R
     W.W.[.].BB
  

  • L and R are adjacent

This one is a bit tricky. At first glance it seems that is always convenient to capture the black pawn, but the following example proves it wrong. For example, consider -

  W.WBBB
  

In this case it is better to move pawn at column 1 to column 2 instead of capturing the pawn at 4. However, it is also possible to find configurations where it is optimal to capture. So we have to check two possibilities.

  • If Whites does not capture the pawn in his first move, then he will never capture it in the future (Otherwise it would be optimal to capture in the first move itself), that means that Blacks will capture pawn L, the game is equivalent to a game where pawn at position L does not exists as black will anyways pass through it. Therefore the problem is reduced to the first case.

  • On the other hand, if Whites decides to capture, then in the next move blacks can again capture or not. And there will be no more immediate captures since the new central pawns will be separated by at least once cell. Again the problem is reduced to the first case.

Note that to find C or compute SW and SB takes linear time. And the case 2 above takes place only constant times. So, overall complexity is linear.

SOLUTION:

Setter

Tester

Time Complexity:

$O(N)$, per test case.

Space Complexity:

$O(N)$

CUTBOARD - Editorial

$
0
0

Problem Link:

Practice

Contest

Setter: Alei Reyes

Tester: Triveni Mahatha

Editorialist: Triveni Mahatha


Difficulty:

CAKEWALK

Prerequisites:

None

Problem:

Given N x M chessboard. Make cuts on some of the edges but don't cut the board into pieces. How many maximum such cuts can you make?

Explanation:

Note that we can make cuts between every two consecutive row of cells. There will be N - 1. Such rows to be cut. Within a row we can make M - 1 cuts. This way of cutting will make the board look like an extended E - shape structure. Refer to the figure for more understanding -

So number of cuts is $(N - 1) \times (M - 1) $

See code below -

    int T = readInt();
    while(T --> 0) {
       int n = readInt();
       int m = readInt();
       int ans = (n - 1) * (m - 1);
       printInt(ans);
    }

Image - Insert Image Here

SOLUTION:

Setter

Tester

Time Complexity:

$O(1)$, per test case.

Space Complexity:

$O(1)$


HAMEL - Editorial

$
0
0

Problem Link:

Practice

Contest

Setter: Alei Reyes

Tester: Triveni Mahatha

Editorialist: Triveni Mahatha


Difficulty:

HARD

Prerequisites:

Matroid Partition, Augmenting Path

Problem:

Given a highly connected (min cut > 3) multi graph G(V, E), find an Eulerian Path from some subset of E.

Explanation:

Every 4-edge connected graph has 2 edge disjoint spanning trees. Given two edge disjoint spanning trees, is possible to choose some of the edges and create an Eulerian subgraph H as follows:

  • Paint the edges of the two spanning trees, the first one in red, and the second in green.
  • Add all the edges of the green tree to H.
  • Root the red tree in an arbitrary node, this will create a parent-child relationship.
  • Let's go through the red tree from leafs to root. Suppose that we are at node u. If the degree of u in H is odd, then add the red edge that joins u with its parent to H.

At the end of the algorithm, all the vertices in H will have even degree. In particular note that the root can not have odd degree because every graph has an even number of odd degree vertices.

To find two disjoint spanning trees in a given graph G, we can use the following algorithm:

  • Let's find an spanning tree T, and paint its edges with color red.
  • Now let's find a spanning forest F that doesn't use edges of T and paint its edges with color green.
  • The green forest is composed of many disconnected trees. Let's call the red edges that joins two disconnected components of the green forest as "connectors"
  • If F consists of exactly one tree, then we are done.
  • Otherwise we'll try add one by one the edges that are not painted keeping always a red tree and a green forest (at the end the green forest will become a green tree!).
    • Let's suppose that we are adding edge e, it will generate a cycle in both the red tree and the green forest.
    • In order to add e we'll have to change the color of some of the other edges.

  • The idea is that e creates a cycle in the red tree, so if we make e of color red, then we have to change the color of one of the edges of the cycle to color green, however this can again create a cycle in the green forest, so we'll have to find one edge of the green cycle and change its color to red, but this can create a cycle in ... (and so on) this process can finish if we end up in a connector
  • Let's build a graph where its vertices represents the edges of G, and there is a directed edge between two vertices x, y if it is possible to replace y by x in its respective tree without generating cycles. Now the previous step is equivalent to finding a path from e to a connector in this new graph. Note that this is similar to finding an augmenting path in flows algorithms.

The algorithm described above is actually the matroid partition algorithm. For a formal proof in the more general setting of matroids, you can see Lecture 13 of Goemans.

SOLUTION:

Setter

Tester

Time Complexity:

$O(VE)$, per test case.

Space Complexity:

$O(E + V)$

CS Academy Round #51 (Div. 2 )

$
0
0

Hi all,

I would like to invite you to CS Academy's next contest which takes place today. You will have to solve 5 problems of varying difficulty in 2 hours.

You are welcome to join. Good luck!

CLFIBD - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Avijit Agarwal
Tester and Editorialist:Soumik Sarkar

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Strings, Sorting

PROBLEM:

Given a string $S$ find the frequency of each character in the string and check whether they can be rearranged into a sequence $F$ where $F_i = F_{i-2} + F_{i-1}$ holds for all $i \ge 3$.

EXPLANATION:

Finding the frequency of each character can be done in linear time. One possible way is below

m = empty map
for each character c in S:
    if c in m:
        m[c] = m[c] + 1
    else:
        m[c] = 0
F = empty list
for each key, value in m:
    append value to F

Next we can say that because $F_i = F_{i-1} + F_{i-2}$ and $F_{i-2}$ cannot be $0$, $F_i > F_{i-1}$ for all $i \ge 3$. So it makes sense to sort the array $F$.

Then we can check if $F$ satisfies the given condition for all $i \ge 3$. If it does, then the string is dynamic otherwise it is not, right? ......But hold on, there is a catch. Indeed $F_i > F_{i-1}$ for all $i \ge 3$, but what about $F_2$? The relation between $F_2$ and $F_1$ is not specified. So it maybe that $F_4 \ne F_2 + F_3$ in the sorted order but $F_4 = F_1 + F_3$. In that case if we can simply swap $F_1$ and $F_2$ to get the required sequence and the string is dynamic.

For example: $F = (1, 2, 3, 4)$. Here $3 = 1 + 2$ but of course $4 \ne 2 + 3$. If we swap $1$ and $2$ we will get $(2, 1, 3, 4)$ where $3 = 2 + 1$ and $4 = 1 + 3$.

sort F
N = length of F
if N >= 4 and F[4] != F[2] + F[3]:
    swap(F[1], F[2])
ok = True
if N >= 3:
    for i in [3..N]:
        if F[i] != F[i - 1] + F[i - 2]:
            ok = False
if ok:
    S is dynamic
else:
    S is not dynamic

AUTHOR'S AND TESTER'S SOLUTION:

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

CUTPLANT- Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Stepan Filippov
Tester-Misha Chorniy
Editorialist-Abhishek Pandey

DIFFICULTY:

MEDIUM

PRE-REQUISITES:

Square Root Decomposition, or Segment Trees, or Data Structures such as Deque

PROBLEM:

Given an array $A[]$ representing height of plants, and another array $B[]$ representing the required height of plants, find minimum time taken to convert array $A[]$ to array $B[]$ using the specified operation. The operation is, choose valid indexes $L$ and $R$ and a target height $H_i$ and cut all plants in the range to height $H_i$. Their initial height must be $\ge H_i$ for this to be valid.

QUICK EXPLANATION:

We can clearly see that the only way of saving time is to make a valid operation in which maximum number of plants need to be cut to same height $B_i$. The problem hence boils down to, making the optimal query by finding such $L$ and $R$ and checking if its valid or not. The case where answer is not possible is trivial to check.

EXPLANATION:

View Content

So, as some of you might have perceived, we will be discussing three approaches here. First we will discuss my approach which is $O(N)$, and then we will see Misha's (tester) $O(N\sqrt{N})$ approach and finally discuss how we can convert/optimize it to become $O(NlogN)$ approach of the setter.

1. Editorialist's Solution-

The very first thing we see is if the answer is possible or not. Clearly, no answer is possible if for some plant $i$, its current height $A_i$ is less than the required height $B_i$. If its possible, we proceed further.

First I will try to give the intuition. See what the problem demands. How can we save time? We can save time for every valid query which sets multiple plants to same required height $B_i$. Hence the problem boils down to proper identification of $L$ and $R$ for the query, and checking if such a query can be made or not.

The first problem which we face in brute force is that, to verify the query is possible, we might have to check all plants and their required heights in range of $L$ to $R$. Not to mention getting exact $L$ and $R$ for query might seem problematic to some. Perhaps we can make some observations first to make our life simpler?

  • Optimal query will have to set at least one plant to its required height. Hence, its value must be between one of the values $B_i$ such that $L\le i\le R$.
  • We further refine our first observation, claiming that the query height must be $max(B_i)$ for $L\le i\le R$. Because if its not so, one of the plants will be cut well below its required height!

Also, imagine if we "have got the required $L$ and $R$" where we got multiple plants which are to be set to same height $B_H$ and are checking if the next element can be included in the range. When will we discard this element at index $i$ from being inside the valid query? We will do so if-

  • If the required height of $B_i$ is more than $B_H$.
  • If the plant height $A_i$ is less than $B_H$.

With these two principles in mind, lets move towards the solution. I will first describe my algorithm, and then we will discuss what it does, and why is it correct.

  1. Make a deque/list/appropriate data structure which supports insertion and deletion at both ends.
  2. For all plants in range $1$ to $N$, do following-
  3. If my deque is not empty, and the current plant (at index $i$) being considered has a required height $B_i$ which is more than the height at the back of deque, keep popping from back of deque till height at back ($B_j$) satisfies $B_j \ge B_i$ .
  4. Now check if the height of plant at $i$, (i.e. $A_i$) is less than the required height $B_L$ at the front of deque. If yes, keep popping from front till this condition becomes false.
  5. After performing step 3 and 4, we can assure that we can make a valid query for all plants currently in the deque, because steps 3. and 4. assure that $B_i$ are stored in descending order, and that the height of final plant $(A_j)$ is sufficient enough to execute query from start to end of deque.
  6. Now check if required height of the plant ($B_j$) at back of deque is equal to required height of plant in consideration ($B_i$). If yes, then we can successfully make a query from the last element of deque to current element, saving an operation. If we find that $B_i \neq B_j$, then we cannot save an operation and must increment time needed by $1$.

Why is this correct?

Notice that, we maintain the condition that, element is in the deque only if its possible to make a query from plant $B_L$ at start of deque to plant at end of deque/plant being considered right now ($B_R$ or $B_i$). This is possible because $B_i$ gets stored in descending order in deque. Then, we also check before adding a plant if its possible to execute a query from start of deque to it by making sure that the current height of plant being added ($A_i$) is enough to support query for plant at index $L$ (i.e. $A_L$). $L$ and $R$ are, obviously, starting and ending range of query.

Why descending order?

We will discuss this in Setter's approach as well. I will mention my intuition here. Lets take a simple example, we have this configuration of elements in array $B[]$ such that $B[]=\{B_j,B_i,B_j\}$ with $B_j < B_i > B_j$. Can we make a query from $B_j$ at left of $B_i$ to $B_j$ at right of $B_i$ to save time? No, we cannot as it would cut plant $A_i$ to a height less than $B_i$. Hence, once we encounter a $B_i$, we can safely eliminate all previous $B_j$ which are smaller than $B_i$ as we cannot make a query from them across $B_i$. Also, any queries which could had been done before $B_i$ had already been considered when we added the element $B_j$ and every other element thereafter.

Hence, the algorithm is correct.

$Time$ $Complexity-$ $O(N)$

Tester's Aprroach-

The tester follows Square root decomposition.

If you got the intuition (even if only a little) of my solution, then this one is even easier. What Misha did after taking input is, he made two buckets. First bucket $sqa[]$ stores minimum height of plant $A_i$ in the range of bucket, and second bucket $sqb[]$ stores the maximum of the required heights height $B_i$ in range of bucket.

Then, he checks if the configuration is valid or not. While doing so, he also makes a vector of pairs, which stores $< B[i], i> $. He sorts this vector in descending order. Now, he does the following-

  1. If required height and current height of plants being considered are equal, do nothing. Else, goto 2.
  2. If this is the first element being considered, or if the required height $B_i$ of this element is not equal to the required height of previous plants, $B_z$ which we were considering, add $1$ to answer and set $B_z=B_i$ and set the index of plant being considered (index $z$) to $i$. Go back to 1. and consider next plant.
  3. If required height of this plant $B_z$ is equal to required height of previous plant being considered, get the index $y$ to that previous plant in the original array (He had made pairs of $< B[i], i> $ for this purpose). Now check if we can make a valid query from the previous plant's index $z$ to this index $y$. This checking happens in $O(\sqrt{N})$ on basis of the observations about invalid queries I mentioned earlier (i.e. if there is a $B_k$ in between which is more than $B_z$ preventing valid queries across it, or if current height $A_k$ of some plant is less than the required height $B_z$). If the query is possible, do nothing, else add $1$ to answer and set current plant of consideration to plant at index $y$. (i.e. set $B_z=B_y$ and $z=y$.)

$Time$ $Complexity-$ $O(N\sqrt{N})$

Setter's Solution-

Basically, the change is in his' and tester's solution is in the step where we check the possibility of queries. He optimizes the step where we check if the query is valid or not.

What he observed was, that, consider two queries which set height of plants (in some range) to $H_i$ and $H_j$. Now, suppose $H_i$ happens after $H_j$, and $H_i > H_j$. He observed that, we can swap the order of these two queries, i.e. execute query $i$ before query $j$ without any effect on the final answer. This is because, any plants getting affected by both query $i$ and query $j$ can be ultimately reduced to height $H_j$ because $H_i > H_j$. He uses this to argue that, there always exist a solution where queries are executed in non-increasing order of heights $H_q$. That is, he will execute query which with greatest height $H_q$ first, &etc. This also justifies tester's step of sorting the vector on basis of required heights $B_i$, as each optimal query will make height ($A_i$) of at least one plant equal to its corresponding required height $B_i$.

With this clear, the only difference comes in checking if the query is valid or not. If we closely see what tester did, and what my definitions say about invalid queries, we can reduce it to finding maximum required height $B_i$ in the range of $[L,R]$ and minimum current height $A_i$ in the range $[L,R]$ where $[L,R]$ are the range of query. This can be easily done via appropriate data structure like Segment Tree & similar.

$Time$ $Complexity-$ $O(NLogN)$

SOLUTION:

Setter
Tester
Editorialist

Commented Solution of Editorialist

CHEF VIJJU'S CORNER:

1. This is a very fit data structure problem, and is really beautiful in this way. There are very little problems where you can solve the question elegantly using the apt data structure. The correct code of algorithm with deque was hardly 6-7 lines for me. This question is really appreciable in this regard, and we must appreciate the setter for such an interesting question.
2. As you can see, the setter and tester have $O(N\sqrt{N})$ and $O(NLogN)$ solutions respectively. The best part of being an editorialist is you can claim the best solution for your share :D :p
3. I will like to leave out some of the apt problems on data structures which I found elegant-

"Can you answer this queries" problem from SPOJ?

$
0
0

I was solving GSS1 - Can you answer these queries I problem from SPOJ, but I have one query in statement Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }, does this mean we have to find max sum subarray with in the given range.

Please explain approach to solve this problems in details.

Viewing all 39796 articles
Browse latest View live


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