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

WA in one test case in question (Chef And Easy Xor Queries)

$
0
0

In this question I am getting wrong answer in one of the test case . here is my solution

any help would be appreciated .


Is the Partition the Graph checker correct?

$
0
0

I didn't want to ask during the contest, but I felt like my solution was correct, yet still got WA. I haven't seen an editorial for the problem yet so I have no way to verify my solution.

So I'd like to ask for a test case that my method fails.

My Approach I picked a root node in the tree (Usually 1, but I tried others) and calculated the distance to each node from there, using Breath First Search/Dijkstra.

I then grouped the nodes into 4 groups with each node going into the group number dist_from_root%4

If group(0) + group(2) == group(1) + group(3), Then the answer is 1 and the sets are chosen in the same way

If they not equal I moved only nodes from one of the groups across to the other side until they were equal, but making the answer 2.

Solution Codehttps://www.codechef.com/viewsolution/22349636

Please help me find a failed test case, I've tried to find my error but could not.

Why doesn't Codechef put editorials of all problems !

$
0
0

Is there nobody answerable to providing editorials of contest problems. Let go other open and unrated contests, we are talking about monthly rated contests. Several times the editorials don't appear not even the unofficial ones, particularly to tough problems. Besides, not to ignore the fact that for even the other problems it takes a minimum of 3 days to put the editorials.

https://www.codechef.com/LTIME67A/problems/NOSS

Come on Codechef, this hasn't happened the first time.

MXDIST - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Bogdan Ciobanu
Tester:Xiuhan Wang
Editorialist:Taranpreet Singh

DIFFICULTY:

Hard

PREREQUISITES:

Convex Hull, Rotating Calipers, Range Minimum Query (RMQ) and bucket decomposition.

PROBLEM:

Given $N$ points and $Q$ queries $(f,t)$ specifying range $[f,t]$, find the maximum squared euclidian distance between any pair of points within the specified range.

QUICK EXPLANATION

  • Divide the points into buckets and build a convex hull for each bucket (preferably using Monotone Chain algorithm).
  • Build an RMQ sparse table considering each block as one unit, rmq[i][j] representing the convex hull formed by points from blocks in the range $[i,i+2^j-1]$. Hulls should be merged in $O(S)$ where $S$ represent the size of the hull.
  • Most distant point pair from a set of points can be easily found by using Rotating Calipers on the convex hull of the given set of points. To answer a query, make a convex hull consisting of points belonging to partially filled buckets and merge it into the appropriate pre-built convex hull from RMQ for intermediate blocks and calculate the answer.

EXPLANATION

Let us solve a trivial problem first. Given a set of points, find the maximum distance between any pair of points.

Lemma: The pair of points having the maximum distance lie on convex hull formed by points.

Proof: Let us assume we have a point pair AB being the most distant point pair, Point A strictly inside the convex hull and point B on or inside convex hull. Lt us extend this line toward A till it intersects the border of the convex hull, say at segment CD. Now, it can be seen, that at least one of $|BC| > |BA|$ or $|BD| > |BA|$ holds, which contradicts the fact that points $AB$ have the maximum distance. This contradicts our assumption. Hence, for the points to be most distant, both points shall lie on the convex hull.

Now, to find the maximal distance, we can use the rotating calipers technique, explained in brief below.

Let us have a pointer variable p and for every point indexed i, move it forward till the distance of (p+1)th point from the line formed by ith and (i+1)th point is more than distance of pth point from same segment, considering distance of pth and (p+1)th point from ith point. whenever moving from ith point to (i+1)th point, consider its distance of both these points from pth point. The maximum of all these is the distance of most distant point pair.

An important point to note is, that binary search is not going to work, as explained well here.

Merging Convex hulls

We merging convex hulls naively (assuming Monotone Chain algorithm is being used). In Monotone Chain algorithm, we find the points having leftmost and rightmost x-coordinate and build lower and upper convex hull separately. So, while merging, we can use merge-sort type technique to merge lower and upper hulls and removing the useless points in time proportional to the size of the convex hull.

Returning to original problem, we can build a RMQ sparse table, where RMQ[i][j] represent the convex hull formed by points in range $[i, i+2^j-1]$ which can be easily rewritten as the convex hull formed by merging RMQ$[i][j-1]$ and RMQ$[i+2^{j-1}][j-1]$. The details of RMQ can be found here.

Now, Let us evaluate the time complexity of this solution. During preprocessing, we have $log(N)$ levels having $N$ convex hulls. We can see, that merging convex Hull take time proportional to the size of convex hull, resulting in preprocessing time being $O(N*log(N)*S)$ after which, each query may take $O(S)$ time as both merging convex hull and calculating most distant point pair take $O(S)$ time.

Now, the question is, what is the size of the convex hull? We have randomly generated points in the second sub-task while worst cases in the third sub-task. It can be seen from research that the expected number of points in convex hull of $N$ randomly generated points is roughly of the order of $N^{1/3}$ while if we generate points carefully in $MX*MX$ grid, we can have up to around $MX^{2/3}$ points in convex hull, $MX = 2*10^5$ in our case. This explains the difference in time complexity of the same solution for second and third sub-task. See references here and here.

Now, we see, though it may be sufficient with optimizations to pass this solution for the second subtask, it shall be hard to pass the final subtask. So, Let us optimize the preprocessing part to fit the time limit by bucket decomposition.

Let's first divide all $N$ points into blocks of size $SZ$ and now, build RMQ considering each block as one position in RMQ. This way, to answer queries, we can use RMQ to find convex hull formed by points in intermediate blocks and naively build a temporary convex hull by points which lie in partially filled blocks (can be at most 2 for each query). We can merge these two blocks and calculate the answer for this block.

Now, Let us calculate the time complexity of this solution. If $C = \lceil N/SZ \rceil$, we can build RMQ on blocks in $O(S*C*log(C))$ time and answer each query in $O(SZ+S)$ time, resulting in time complexity $O(S*(N/SZ)*log(N) + Q*(S+SZ))$. It works fast enough for $SZ = sqrt(S*N*log(N)/Q)$.

Editorialist solution

The editorialist who like different solutions, choose to use graham scan as means of building and merging convex hulls as opposed to Monotone Chain algorithm in case of setter and tester solution. This slows down editorialist's solution by $log(S)$ due to the fact that for Graham scan, sorting by the polar angle is required while in Monotone Chain algorithm, merging convex hull can be done in merge sort type manner in $O(S)$ for both lower and upper hulls. This is the reason Monotone Chain algorithm is preferred to Graham scan in this problem.

An interesting problem to try is GEOCHEAT.

Time Complexity

Overall time complexity is $O(S*(N/SZ)*log(N/SZ) + Q*(S+SZ))$ where $SZ$ is the block size chosen.

Space Complexity is $O(N+S*(N/SZ)*log(N/SZ))$.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution
Tester's solution
Editorialist's solution

Feel free to Share your approach, If it differs. Suggestions are always welcomed. :)

Rating not updated.?

$
0
0

Rating is not updated for External contest Plinth-Enigma'19 LNMIIT Techfest - (Rated for all)?? My rating before above contest is 1484.And After that, it inc. by 83.So 1567.And For accidental purpose of JAN Long challenge.It is Dec.by83.So 1484 as above. After Jan Long challenge It will 1581.So I think Above Contest rating is not added.

GMEDIAN - Editorial (Unofficial)

$
0
0

PROBLEM LINK:
Div1
Div2

Setter:Teja Vardhan Reddy
Editorialist: Utkarsh Pandey

DIFFICULTY:
EASY

PRE-REQUISITES:
Observation, Binomial Coefficients.

PROBLEM:
Given a sequence A1,A2,…,AN. Find the number of subsequences in which the median of the subsequence is present in that subsequence, modulo 1000000007.

Explanation
Since we have to sort each subsequence to find its median, we will sort our original sequence (i.e. A1,A2,…,AN) at first itself. The ordering won't change.
For example, the good (desired) subsequences in the sequence [9,5,7,6,8,1] are same as that in the sequence [1,5,6,7,8,9].

The subsequences having odd length will definitely qualify to be one of our good subsequence (as in the subsequences with odd length, the element at the middle position is the median of the subsequence itself).

The subsequences with even length will qualify as good subsequence if and only if the middle two elements are same. It is so because the array is already sorted. View the content below in case you didn't understand this statement.

View Content

So our answer to this problem is : (Number of subsequences having odd length) + (Number of good subsequences having even length with both the middle elements equal)

First Subtask:
It is clearly written in this subtask: A is a permutation of integers 1 through N. Also, the number of elements in the sequence A is N which means each element from 1 to N is present once and only once. This tells us that there is no repetition of any number. So, no subsequence having even length will be counted.

So, answer to this subtask = Number of subsequences having odd length
= Number of ways of selecting 1 out of n elements + Number of ways of selecting 3 out of n elements + Number of ways of selecting 5 out of n elements + ............. + Number of ways of selecting n or (n-1) out of n elements

$=nC1 + nC3 + nC5 + ..... + nCn$ (if 'n' is odd) or $nC1 + nC3 + nC5 + ..... + nC(n-1)$ (if 'n' is even)
where nCx denotes the number of ways of choosing x elements out of n elements

= 2^(n-1) See the proof below if you didn't understand this completely Proof:

View Content

Second and Third Subtask:
The tricky part of this question is when the elements in the sequence starts repeating. In this case, we have to find the number of subsequences having even length. To find the subsequences of even length to be a good subsequence, we traverse through each element which is repeated at least once. For this element to be our median element in one of the subsequences of even length, we must have at least k elements at its index's left and we must have at least k elements at the other element index's right (Note that our array was sorted), where k is a non-negative integer.
An example is provided in the section below in case you didn't understand the lines written above:

View Content

Now, Calculating nCx in each iteration, we may have difficulties passing the time limit provided in the problem. To reduce the time complexity to pass the given time limit, we have to observe the given fact:

Let the repeating elements be found at index i and j Suppose, there are m elements at the left of the index i and n elements at the right of index j.

So, number of good subsequences: 1 (good subsequence of length 2) + $mC1 * nC1$ (good subsequences of length 4) + $mC2 * nC2$ (good subsequences of length 6) + ........... + $mCmin(m,n) * nC(min(m,n))$.

By Vandermonde's identity we can sum up this value as (m+n)C(min(m,n)), details of which can be found here :Vandermonde's Identity.

Bonus: Calculating queries of the type nCr % 1000000007 can be solved by precalculating $nCr % 1000000007$ upto n = whatever you need :p . Details of this can be found here: nCr % p in O(1)

Time Complexity = O($N^2$) (Enough to pass all the subtasks)

Editorialist's Solution:https://www.codechef.com/viewsolution/21611480

A very big plagiarism this long challenge JAN19.

$
0
0

Codechef did not do his job this long challenge yet it was obvious that the plagiarism had to be very big. Out of 10 solutions in python3.6 I count 4plagiarisms on XYPIZQ.

And what disgusts me is that the scores of all these cheats have been calculated. Some of them were just copying and others using other techniques that I prefer not to say here so that others do not use it.

This attitude was common in India and I find it very sad to behave when I see all the work done by codechef, geeksforgeeks and ... This is not the way that India will stand out as a respected power. Please stop the plagiarism because I know people who prefer not to participate because of it. Even his ranking backward gradually because of the people who cheat is frustrating.

Look at these solutions:https://www.codechef.com/viewsolution/22482771https://www.codechef.com/viewsolution/22482425https://www.codechef.com/viewsolution/22483248https://www.codechef.com/viewsolution/22482660

Just in one page.

And this is about all the problems of competition

GetCode Codechef/Codeforces/SPOJ plugin for Sublime Text 3

$
0
0

GetCode

This is an ST3 plugin which:

  1. Take the URL of a problem such as https://www.codechef.com/problems/INVLIS.
  2. Parse the URL and get the problem code(In this case it is INVLIS).
  3. Create a new .cpp or .py file with a pre-determined template(cpp.snippets which is customized via settings).

Keyboard shortcuts

For all Operating Systems, ctrl+alt+x opens a new dialogue box which takes the problem url as user input

How to install

  1. Install Package Control from here
  2. In Sublime, Open Package Control

Open Package Control from the Preferences Menu

  1. Select Package Control: Install Packages

enter image description here

  1. Now you should be able to search for and install the GetCode Package.

How to use it

After installing, it is necessary to configure the settings(setting the default directory and snippets).

After configuring the settings, ctrl+alt+x opens a new dialogue box which takes the problem url as user input

Supported websites(for now)

  1. Codechef
  2. Codeforces
  3. SPOJ
  4. Virtual Judge

Getting java NZEC error on codechef compiler

$
0
0

Guys i am trying to solve the DAG Delete problem of December contest. My code runs perfectly fine on my computer and i have tested it for multiple cases. I have also made sure that everything is properly initialized and checked for corner cases too. Earlier i was using too much memory and even that is not the case now. Please tell me what are the not so common reasons where you people got Run Time Error or how should i proceed with debugging my code.

Best Regards

Ratings are just unfair..!!!

$
0
0

Ratings are just unfair..!!

  • My rating before(this and JAN Challenge) is 1484.
  • And after this challenge +83.So 1567.And it is reverted back to 1484.Due to running of JAN Long challenge.
  • And after long challenge it is inc.by +97 ,which is 1581.
  • And Now ratings are updated 1567(this External rating contest ).And +14 for Jan Long challenge.
  • This is so unfair because my rank was 2673.which is 1/4th of 13,000 participants.
  • And I get +14..Need to go through once.@admin@vijju123.

MySql database creation

$
0
0

Need help how to create database in mysql via chef .Iam able to install mysql and now i need to create database i don't know the syntax how to create database.Thanks .

this code runs successfully but at the time of sumbit it gives me NZEC error . can you help me to rid off from this

$
0
0

cook your code here

x, y = int(input()), int(input()) if(x % 5==0): print(y) y=y-x- 0.50 print("%.2f" %(y) ) else: print(y)

A big bug in Rating system..!!!

$
0
0

Here,

  • It is my rating graph for Jan Long Challenge 2019(Div.2),And see my rating inc. by 14.So which becomes 1581.
  • And my Rank was 2673.

My Graph

  • And this is Another graph of the person from same rank list,which is inc.by +26,which becomes 1590.
  • And his rank was 3990.

His graph

And,My rank was more than him,but his rating inc.by +26,but mine was +14...Give me reason @admin@vijju123 Thank you..!!!

Help for SEACO

$
0
0

hi , i am not able to find out whats wrong in my solution for the problem "Sereja and Commands"(https://www.codechef.com/problems/SEACO ) . I am implementing a fenwick tree approach , in which i am applying all the commands of type "1" in my array a all commands of type "2"are pushed in a vector, then i am traversing the vector from back and implementing all the commands of type "2" on another BIT one by one .The second BIT is used for storing the count of all the commands with particular index , then finally implementing all the commands of type "1" on my array a . map 'c' and 'd'are used for the storing the type and range of the a particular command respectively. I checked in the editorial discusions that my approach is correct but not able to find the error in my code. my submission link (https://www.codechef.com/viewsolution/22518842 )

FANCY - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Shivam Gupta
Tester:Xiuhan Wang
Editorialist:Taranpreet Singh

DIFFICULTY:

Cakewalk

PREREQUISITES:

None

PROBLEM:

Given a string, check if it contains the word "not" as a complete word. (Not as a part of another word, like nothing)

SUPER QUICK EXPLANATION

  • The quote is Real Fancy, if the quote is "not", quote begin with "not", quote ends with "not" or quote contains "not" where "*" represents space character.

EXPLANATION

Consider the special case where quote itself is "not" separately.

After this, the word "not" can either appear as the prefix, as the suffix or in between the quote. So, check separately if the first word is "not", the last word is "not" or the quote contains the word "not". (Make sure to check that the word "not" is surrounded by space character on both sides.)

Trick

Those not interested in splitting the string into words can solve this by inputting the quote as a string, add space character at both ends of strings. Now, the quote will be "Real Fancy" if it contains "not" where "*" represents space character.

As a side fact, @vijju123 actually have a thing about fancy quotes. He has another fancy quote, shared during the contest, "You made my non-fancy quote a fancy one".

Time Complexity

Time complexity is $O(|S|)$ per test case where $|S|$ is the length of the quote.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution
Tester's solution
Editorialist's solution

Feel free to Share your approach, If it differs. Suggestions are always welcomed. :)


MGAME - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Smit mandavia
Tester:Xiuhan Wang
Editorialist:Taranpreet Singh

DIFFICULTY:

Easy

PREREQUISITES:

Modulo operator and Basic Combinatorics.

PROBLEM:

Given two integers $N$ and $P$, suppose the maximum value of $(((N \bmod i) \bmod j) \bmod k ) \bmod N$ be $M$ where $i, j, k \in [1, P]$, Find the number of ways to select $i, j, k \in [1, P]$ such that $(((N \bmod i) \bmod j) \bmod k ) \bmod N$ equals $M$.

SUPER QUICK EXPLANATION

  • The maximum value of $N \bmod x$ where $x \in [1,N]$, if $N$ is odd, is $(N-1)/2$ when $x = (N+1)/2$, and if $N$ is even, is $N/2-1$ when $x = N/2+1$.
  • We can achieve $(((N \bmod i) \bmod j) \bmod k ) \bmod N = M$ in three ways. Let $x = \lceil (N+1)/2 \rceil$
  • $i = x$ and $j,k > M$.
  • $i > N$, $j = x$ and $k > M$.
  • $i, j > N$ and $k = x$. Each of this case can be easily computed.

EXPLANATION

First of all, Let is find this value $M$. It has to be less than $min(i,j,k,N)$ which implies, $M < N$. Hence, if we want $M > 0$, we need $(((N \bmod i) \bmod j) \bmod k) < N$. So, We know for sure, that to maximize $M$, $min(i, j, k) \leq N$. Hence, we need maximum $(((N \bmod i) \bmod j) \bmod k) < N $ and now we can ignore the last $\bmod N$.

So, The maximum $N \bmod x$ can attain is $\lfloor (N-1)/2 \rfloor$. This happens when $x = \lceil (N+1)/2 \rceil$. It can be easily verified either by checking by hand, or writing a simple program ;)

Now, try finding out number of ways $(((N \bmod i) \bmod j) \bmod k)$ equals $M$. It can be approached in Simple case base analysis.

We can try all possible triplets of $(i,j,k)$ and generalize them into three cases.

  • When $i = \lceil (N+1)/2 \rceil$ and $j,k > M$
  • When $i > N$, $j = \lceil (N+1)/2 \rceil$ and $k > M$
  • When $i,j > N$ and $k = \lceil (N+1)/2 \rceil$

In all three cases, we can simply count the number of triplets $(i, j, k)$ satisfying any condition and print the answer.

Corner Case

When $N \leq 2$, $M = \lfloor (N-1)/2 \rfloor = 0$. This is because we cannot achieve $(((N \bmod i) \bmod j) \bmod k ) \bmod N > 0$. So, all triplets $(i, j, k)$ are valid.

Alternate solution - read at your own risk, you have been warned :D

For those curious enough not to be satisfied with such solutions, there also exists a pattern based solution too, using basic math. Just use brute solution to find the first terms of series and solve using the pattern formed. Number 6 is important. Enjoy :D

Time Complexity

Time complexity is $O(1)$ per test case.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution
Tester's solution
Editorialist's solution

Feel free to Share your approach, If it differs. Suggestions are always welcomed. :)

A doubt in approach of MAXEP problem ( Shared by IOI Gold Medalist ) - December long contest 2018

$
0
0

I wrote an editorial regarding how to solve the MAXEP problem asked in december long contest 2018.

A lot of users shared wonderful approaches to take on the problem (besides my way of solving it), but I was not able to understand the approach of @utaha.

So any-one who understands how @utaha solved that particular problem - Please help...!!!

Especially I would be glad if @utaha himself helps me...!!!

That approach was ( as @utaha mentioned in the editorial ) from an IOI gold medalist and sounded very simple, just the fact was that I was not able to understand why was it working...

Link to that editorial can be found HERE

I asked my doubts there in the comments section ( Just under where @utaha shared his approach), but I guess no one is looking at that editorial now... So I decided to ask it seperately here.

But if you get @utaha's approach, Please share it in that editorial itself. ( It will be good for me to have all material of one question under one link itself)

Thanks in Advance...!!!

Invitation to CodeChef January Long Challenge 2019 sponsored By ShareChat

$
0
0

Happy New Year to the CodeChef community!

Celebrate the new year with CodeChef’s January Long Challenge 2019 sponsored by ShareChat. This programming contest lets you tackle 8 problems over 10 days and it’s open to programmers in every country and at every skill level. The contest problem statements will also be available in English, Hindi, Bengali, Russian, Mandarin and Vietnamese.

Participants will also have the opportunity to apply for jobs at ShareChat - India’s fastest growing social network. Visit the contest link for more details.

I hope you will join your fellow programmers and enjoy the contest problems. Joining me on the problem setting panel are:

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: 4th January 2019 (1500 hrs) to 14th January 2019 (1500 hrs). (Indian Standard Time — +5:30 GMT) — Check your [timezone](https://www.timeanddate.com/worldclock/fixedtime.html?msg=CodeChef+January+Challenge+2019&iso=20190104T15&p1=44.

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

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. First to solve each problem except challenge - 100 laddus. 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 !!

PARRTY - EDITORIAL

$
0
0

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter:Mohammad Nematollahi
Tester:Xiuhan Wang
Editorialist:Taranpreet Singh

DIFFICULTY:

Medium-Hard

PREREQUISITES:

Segment Tree and Implementation would do.

PROBLEM:

Given $N$ people numbered $1$ to $N$ and $M$ conflict pairs of people, answer $Q$ queries of format. Given $K$ pairs in a query namely $[L_i, R_i]$ inviting all people in range $[L_i, R_i]$ to party. Determine if all people invited to party get along or not.

QUICK EXPLANATION

  • The brute solution to answer each query in $O(N+M)$ time can be easily written. This solution takes $O(Q*(N+M))$ in the worst case if all queries consist of a single interval of people invited and shall time out.
  • We can develop another solution answering each query in $O(K^2)$ time by iterating over every pair of intervals in the query and checking if both of the intervals contain a pair of people who do not get along. If it holds true for any pair of intervals in query, answer is NO, otherwise YES. This solution too won't work as it may take time to answer if there are too many intervals in few queries.
  • To find out whether any pair of an interval of people contains any conflict pair, we shall use segment tree operations.
  • Now combine the above two solutions, using the first solution when $K$ is large, and the second solution when $K$ is small, to fit the overall solution into the time limit.

EXPLANATION

The solution to this problem is based on merging two slower solutions to fit the time limit, so let us discuss both solutions.

Brute Solution:

To answer each query in $O(N+M)$ time, we can simply maintain an array included, marking all the elements present in intervals and then iterating over all conflict pairs to check if both persons in any pair are included or not. This solution performs well when there are few queries with a high number of intervals.

Segment Tree Solution:

We can also build a solution which, for each query check all pairs of intervals to see if the first member of any conflict pair lies in the first interval and second person of conflict pair lie in the second interval of selected pair. If we tried to maintain a set of conflict pairs, it shall time out. We need something smarter.

Let us store these queries and answer them all together efficiently.

What we can do is, to build a range max Segment tree initially filled with -1 and start considering each person one by one. While considering yth person, Consider all conflict pairs $(x,y)$, $x < y$ and update these positions with value y.

Now, whenever we have an ith interval in query $[L, R]$ where $R$ is the person being considered, we can check all intervals ending before $L$ and check if range max of any interval is always strictly smaller than $L$. The reasoning is as follows.

Considering only first $i$ persons, when we reach the ith person, we update all positions having a conflict with the ith person with value i. Now, If any interval has range maximum x if implies that in that interval, there is a person having a conflict with the xth person. So to check if any conflict pair is there, we iterate over all intervals ending before the current interval and check if this interval has a conflict with any person having index $\geq L$. (Meaning people in the current interval). This compares all unordered pairs of intervals and thus, runs in $O((N+M)*log(N)+\sum K^2)$ to answer all queries.

This solution won't work due to square factor and shall time out when there are few queries with a large number of intervals.

Merging solutions:

Let us define a limit $SQ$. We use brute solution when $K \geq SQ$ achieving worst case when $K = SQ$ taking $O(Q*(N+M))$. This may seem large, but here, $Q*SQ \leq 2*10^5$

We shall use the second solution when $K < SQ$ as our second solution is good in answering queries when $K$ is small. If all queries are answered by this solution, it takes $O((N+M)*log(N)+\sum K^2)$ time. But, since $K < SQ$, $\sum K$ cannot exceed $2*10^5*SQ$.

By choosing a reasonable value of $SQ$, we can achive $O((N+M)*Q/SQ +(N+M)*log(N)+Q*SQ)$.

Implementation hints:

It is useful in the second solution to sort the intervals beforehand so you only need to check intervals indexed up to the current interval. Additionally, do not forget to consider the case when a conflicting pair lies inside a single interval only in the second solution. This can be easily handled by considering the pair of an interval with itself too.

There are quite a number of problems merging solutions, but I don't remember any at present, so please share the link of any problem you know using a similar idea.

Time Complexity

Time complexity of this solution is $O((N+M)*Q/SQ +(N+M)*log(N)+Q*SQ)$ in worst case. Memory complexity is $O(N*log(N)+M+\sum K)$ in worst case.

AUTHOR'S AND TESTER'S SOLUTIONS:

Setter's solution
Tester's solution
Editorialist's solution

Feel free to Share your approach, If it differs. Suggestions are always welcomed. :)

Pizza Slice (XYPIZQ) mini editorial

$
0
0

Consider this diagram. Half of the line segments are drawn in red. The line segments $a_0b_1,b_1a_2,a_2b_3,b_3a_4$ also exist, but are ommited here for clarity.

alt text

We do not yet know what angle $x$ is, but we can work out the other angles in terms of $x$. We will be working in radians here. $\pi\ radians = 180\ degrees$

Because the slice is an isosceles triangle, we can calculate:

$c = \frac{\pi-x}{2} = 0.5\pi - 0.5x$

Knowing that all the inner triangles are also isosceles trangles, we can also calculate:

$d = \pi - 2c = x$

$e = c - d = 0.5\pi - 1.5x$

$f = \pi - 2e = 3x$

$g = \pi - c - f = 0.5\pi -2.5x$

$h = \pi - 2g = 5x$

$i = \pi - e - h = 0.5\pi - 3.5x$

$j = \pi - 2i = 7x$

Also because of the isosceles triangle, $x = i$, so we can now derive the value of $x$:

$x = 0.5\pi - 3.5x$

$4.5x = 0.5\pi$

$9x = \pi$

Now we can go back and substitute $\frac{\pi}{9}$ for $x$ and work out all the angles exactly.

We can also see a pattern in the angles. The angles of the tops of the triangles go:

$x,3x,5x,7x..$

while the angles of the sides go

$0.5\pi-0.5x$

$0.5\pi-1.5x$

$0.5\pi-2.5x$

$0.5\pi-3.5x$

$..$

So we can work out the angles of specific triangles with closed form formula, instead of having to calculate them all.

Viewing all 39796 articles
Browse latest View live


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