prob : http://codeforces.com/contest/913/problem/E
I had read the editorial already but didn't understand it. so, if possible please explain this problem a little bit more !
prob : http://codeforces.com/contest/913/problem/E
I had read the editorial already but didn't understand it. so, if possible please explain this problem a little bit more !
Note that in general, the syllabus for Competitive Programming is open-ended. For ACM ICPC, the syllabus is not mentioned anywhere, whereas IOI syllabus is specified before the start of the contest each year. The below syllabus is kind of detailed topics from which you may face questions in competitive programming related competitions.
https://docs.google.com/document/d/1_dc3Ifg7Gg1LxhiqMMmE9UbTsXpdRiYh4pKILYG2eA4/edit1
Author:Praveen Dhinwa
Tester:Misha Chorniy
Editorialist:Animesh Fatehpuria
There is an equilateral triangle $ABC$ with side length $2 \cdot a$. The coordinates of the triangle's vertices are $A = (-a, 0), B = (a, 0), C = (0, \sqrt{3} \cdot a)$. Next, there are three circles with centers at the midpoints of sides $AB$, $BC$ and $AC$ and radii $r_1$, $r_2$ and $r_3$ respectively. Compute the area of the intersection of the triangle and the three circles. The absolute or relative error should be atmost $0.05$ and $a \le 50$.
First, we note that the desired accuracy for this problem isn't as high as typical geometry problems. Additionally, $a$ is quite small as well. This suggests that we can use a monte-carlo or sampling based solution to approximate the answer with reasonable accuracy. Indeed, it turns out that this is one of the easiest ways to solve this problem.
The first solution (and probably the simplest) would be to partition the triangle into a bunch of really tiny rectangles whose areas sum up to give a good enough approximation of the area of the triangle. We can then iterate over each such tiny rectangle and check whether it lies within the three circles, and if so, add up that area. It turns out that using $0.01 \times 0.01$ rectangles gives a good enough approximation for this problem.
To implement this, we can use the most brute force method possible. Since the area is bounded by $4400$ units, we won't need more than $4400 \cdot 10^4 = 4.4 \times 10^7$ rectangles. Further, checking if a rectangle is valid can be done in $O(1)$ since we just need to check if a point lies inside three circles. Thus overall, this method is fast enough.
Monte Carlo based solution Uniformly sample the points inside a triangle and check whether they belong to the three given circles. You need around $10^7$ (or $5 * 10^6$) samples to get the desired accuracy.
For checking how to uniformly sample the points in an equilateral triangle, see the http://mathworld.wolfram.com/TrianglePointPicking.html. The basic idea is as follows. Let OAB be the triangle where O is at the origin. Now, consider the vector OA and OB. Generate two numbers a, b in the range $[0, 1]$ and the OC be the vector $a * OA + b * OB$. Note that point C is uniformly generated in the parallelogram made by OABD (where point D is such that BD is parallel to OA). If the point C doesn't lie in the parallelogram, then we reflect it across the diagonal AB. This way, the point C will be a uniformly random point inside the triangle.
Another possible way could be sampling from a disk whose radius can be found as follows. Find the centroid D of the triangle. Find the radius R that is the distance between D and any of the vertices A, B, C. Now, randomly sample from a disc of radius R and check whether the point lies in each of the circles and the triangle. This method requires around $10^6$ or more queries to get a good enough accuracy.
There is a deterministic sweep line solution where you can move across the intersecting points and get the corresponding areas by using simple formulas.
Author's solution can be found here.
Tester's solution can be found here.
Author:Satyaki Upadhyay
Tester:Misha Chorniy
Editorialist:Animesh Fatehpuria
Count number of semi-BSTs having exactly $n$ nodes. A semi-BST is a tree with $n$ nodes which satisfies the following conditions:
Constraints: $n \le 10^5,$ $\text{test cases} \le 10^5.$
Print the answer modulo $663224321$ i.e. $2^{19} \times 5 \times 11 \times 23 + 1$.
Knowledge of "online" FFT trick.
We first solve the problem in $O(n^2)$, and then optimize it using a trick.
We use a dynamic program similar to "count number of BSTs having $n$ nodes". Define $T(n)$ to be number of semi-BSTs of size $n$. To find a recurrence for $T(n)$, we will iterate over the number of nodes in the left subtree. Note that fixing the number of nodes in the left subtree determines the value of the root. Suppose we say that the left subtree has $i$ nodes. Then, the number of labeled trees with $i$ nodes is $i^{i - 2}$ by Cayley's Formula. Thus, the number of ways for us to choose a left subtree is $i \times i^{i - 2} = i^{i - 1}$ since we have $i$ choices for the root of the left subtree as well. By definition, the right subtree can be chosen in $T(n - 1 - i)$ ways. Note that these two are independent, making our recurrence:
$T(n) = \sum_{i = 0}^{n - 1} (i^{i - 1} \times T(n - 1 - i))$ with base cases $T(0) = T(1) = 1$.
Clearly, there are $O(n)$ states, and it takes $O(n)$ to compute each state. Therefore, this solution is $O(n^2)$.
It turns out that we can speed up the above dynamic program using a trick known as online FFT. The special modulo would have given this hint as well! For reference, please solve this Codeforces problem. The editorial for this problem explains this trick!
Additionally, you can check out these brilliant slides written by Tanuj Khattar! Interestingly, his team TooWeakTooSlow were the only team to solve this problem in the onsite regional.
The final complexity would be $O(n \log^2{n})$.
Author's solution can be found here.
Tester's solution can be found here.
@admin,@vijju123 rating of cookoff is updated from the ratings which we have got before plagarism check but shouldn't we actually get it from the new ratings after plagiarism checking.please check into the issue because rank predictor also shows we should get more in Nov long according to present ranklist if in Nov long http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/NOV17/all
Can anyone tell me the approach of the third problem( Obtain Desired Expected Value ) of Chennai Onsite . Link of problem
Hello everyone!
Codechef Rating Predictor
The delay in previous month rating changes + inspiration from CF Predictor and for the practice of a web-application, i tried to write a script that can predict rating changes from ongoing live contests @ Codechef.
While the actual delays in rating changes s/would be fixed, this script can help in predicting rating changes as new submissions are made, so hopefully it can be useful for Long contests :).
The script is written in nodejs and is based on open rating formulas available at this link. The code for the project can be accessed here
Website is currently hosted on Openshift free servers and has few restrictions on use. Therefore the server might be slow or not responding during the period rating changes are calculated. Currently, ratings are expected to be updated every 15 minutes
I also tested rating changes on few past contests and the predictions were accurate within an error of 2 for almost everyone except the first rank (I have no idea why first rank predictions are wrong in some contests using current formulas)
Please note that project is still in beta stage and also actual changes might differ more due to changes in ranklist after plagiarism detection
Your feedback/suggestions would be appreciated
JUNE17 Links:
All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/all/
Long: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/long/
Few stats on JUNE17 Predictions. I matched ratings (All) of first 6391 users and the results were as follows:
Difference - No of users
There were around 40 users having difference > 50. Turns out some usernames appears to be missing in the ranklist when sorted by rank and hence they were showing as last in the prediction list.
I ran the code again after fixing the above bug and results are better now (Maximum difference is 8)
COOK83 Links:
All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/all/
Short: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/short/
The ratings are expected to update every 5 minute
Few stats, 4811/4820 predictions (for both all and cook-off predictions) were right. Rest have diff < 3 with the exception of rating prediction of first rank in cook off. Also, as @vikasj554 pointed out, few users got rating changed after initial update. (I still need to figure out why this happened). But even after this 4794/4820 predictions were accurate.
LTIME49 Links:
All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/all/
Lunchtime : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/ltime/
The ratings are again expected to update every 5 minute
JULY17 Links:
All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/all/
Long : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/long/
Update frequency: 10 mins
Medium
Disjoint Set Union
Maintain the size of the most populated region after each query.
The solution of this subtask is to use breadth first search after applying each query to find all the regions' city sets. If we have all the regions' cities sets, we can easily find the maximal populated region.
Let's describe this approach in more details.
Let's denote:
1) Integer array $P$, where $P[i]$ is the population of city numbered the $i$th.
2) Boolean array $D$, where $D[j]$ is true, if the road numbered the $j$th has been destroyed, and false otherwise.
3) Adjacency list $Adj$. We can store this list efficiently, for example, using STL vector in C++. For every adjacent node, let's store a structure, containing the following fields:
Having all this, we can process the queries in the following way:
P $x$ $y$ - change the population of the city numbered the $x$th to $y$. In this case, we just make a single assignment: $P[x]$ = $y$. This operation is performed in $O(1)$.
D $x$ - destroy the road numbered the $x$th. Again, this is just a single assignment ($D[x]$ = true), so it is also performed in $O(1)$.
Now, how to find the size of the maximal populated region.
We will make use of queue data structure.
Let's iterate through all the nodes. Whenever we find a node which was not included in any connected component, we start the breadth first search. Let's describe it in brief:
Let's denote Boolean array $Used$, where $Used[i]$ is true, if $i$th city was added to queue, and false otherwise.
The pseudocode of the algorithm for finding the size of the most populated region is given below.
ans = 0;
For i := 1 to N
used[i] = false
For i := 1 to N
if not used[i]
queue.add(i);
population = 0;
while queue is not empty do
curNode = queue.pop();
population += P[curNode];
For j := 0 to Adj[curNode].Length
if ((not D[Adj[curNode][j].edge]) and (not Used[Adj[curNode][j].node]))
Used[Adj[curNode][j].node] = true;
queue.add[Adj[curNode][j].node];
ans = Max(ans, population);
return ans
The complexity is $O(Q*(N+M))$.
We will use the data structure called Disjoint Set Union.
Let's have $N$ elements numbered $1$ to $N$ and $N$ sets. Initially, the $i$th set contains the $i$th element.
Disjoint Set Union maintains two basic operations:
1) Uniting two sets.
2) Finding the set containing the given element.
The amortized time per operation is $O(\alpha(N))$, where $\alpha(N)$ is less than $5$ for all remotely practical values of $N$.
Note that you don't have to output the size of the most populated region before reading the next query. So, you can read all the queries in advance and solve the task in reverse order.
Assume that all $Q$ queries were performed. Let's add all connected components (regions) to the DSU. Obviously, we can determine the most populated region.
Let's create the DSU with $N$ elements denoting the cities and $N$ sets denoting the regions. Along with each set (say, the $X$th), let's maintain the value of $P[X]$, denoting the total population of the cities in the $X$th set. Now, the DSU corresponds to the road system with $N$ cities, given populations and without roads. Note that we should take the populations that are obtained after the performing of all the queries.
Now, assume that all the queries has already been performed. Then, there is a set of roads, which has not been deleted. Let's add all of them. The addition of the road is simply merging two corresponding sets in the DSU structure. Since we have one non-standard operation here, namely, handling the sizes of the regions, letТs give a pseudocode for it.
Given that we need to add a road connecting the city numbered the $X$th and the city numbered the $Y$th.
Merge (X, Y)
setX = FindSet(X)
setY = FindSet(Y)
if (setX == setY)
return;
SetParent(setY, setX)
P[setX] = P[setX] + P[setY]
Now, let's "rollback" the queries starting with the last one. The "rollback" of the change population query is changing the value of the corresponding $P[X]$, and the "rollback" of the road deletion query is adding the road like we've described above.
Meanwhile, we can also maintain a priority queue of an STL set for determining the size of the largest region quickly. This way, we can answer on the maximal region population in $O(\log N)$.
The complexity is O($N + M \alpha(N) + Q \log N$).
Can be found here
Can be found here
I did the exact same thing explained in the tutorial. It's passing the sample test cases but giving WA when submitted.Please help!
It would be very good if CodeChef could provide a detailed set of test case for a given problem and at what particular test case did a particular code fail. This would be a really good initiative on your part to help people in improving the tiny small errors that are really-really hard to spot and are often committed and never spotted.
CAKEWALK
Basic knowledge of arrays and loops.
The program asks you to calculate if all the elephants would get the number of candies that they want.
If there are C candies in all, and elephant i needs A[i] candies, then it is possible to serve all the elephants only if there are enough candies available, i.e. the following condition must be satisfied:
C >= A[0] + A[
1
] + ... + A[N-1]
This means you can have a simple loop over the array A to count the sum of the required number of candies by the elephants and then finally comparing it with C to determine the answer. If the above condition is satisfied, answer will be Yes, else the answer will be No (they have to be case-sensitive to avoid WA).
Can be found here.
Can be found here.
I want to know how can I get a CodeChef goodie? In which monthly contests, how many goodies are given? Does CodeChef also give certificates to the winners?
Author:Sergey Kulik
Tester:Harshil Shah
Editorialist:Pawel Kacprzak
CAKEWALK
Strings, Implementation
For a fixed set of Latin letters S, for each of given N words decide if it can be formed using only letters from S.
For each of given words, check if all its letters are in the given set of known letters S by iterating over letters in S explicitly or using any data structure with fast lookup operation.
In the first subtask, the set S contains exactly one letter. In this case, it is very easy to decide if a given word can be formed using only letters from S, because there is only one letter that can be used, so for example if the letter in S is c, then all possible words that can be written using it are: c, cc, ccc, …. Since the length of any word in the input can be at most 12, then there are exactly 12 different words for which the answer is "Yes"
. For all other words the answer is “No”
, because each of them contains at least one letter not in S.
In the second subtask, S can contain at most 26 letters. In this case, for a given input word W, we want to check if all its letters are in S. In order to do that, we can iterate over all letters of W and for each one check if it is in S. Since S is very small, that check can be performed actually by iterating over all letters in S explicitly. The answer is “Yes”
if all letters of W are in S, otherwise the answer is “No”
. Thus, for a single word W, the answer can be computed in O(|W| * |S|) time, so the total running time is O(|total_len|*|S|), where total_len is the sum of lengths of all N words in the input.
For a faster solution, first we can store letters from S in any data structure that provides fast lookup - array will work the best here, since there are at most 26 different letters, but hash table is also fine here. If array is used this step building the array takes O(|S|) time. Then, for a given input word W, we can check if all of its letters are in S using the lookup in our data structure. It follows that the total running time of this method is O(|S|+|total_len|), where total_len is the sum of lengths of all N words in the input.
Tester's solution can be found here.
Editorialist's solution can be found here.
Hi all,
I would like to invite you to CS Academy's next contest which takes place on Wednesday. The round will consist of interactive problems, only. There will be some money prizes awarded to the top 2 participants. You can find out more details on the contest page.
You are welcome to join. Good luck!
Cakewalk
ad-hoc
Given a string S, if we split it in the middle (if S has an odd number of characters, disregard the middle character), then if the frequency of each character is the same in both halves, S is called a "lapindrome". Given the string S, test if it is a Lapindrome or not.
Maintain frequencies for the left half and the right half, for each character. After computing the frequency of each half, then check if the frequencies of all characters match. If so, output "YES", else output "NO".
Consider the following pseudocode:
bool isLapin(S)
initialize cntL[] and cntR[] with 0
L = S.length()
for(i = 0; i < L/2; i++)
cntL[S[i]-'a']++
for(i = (L+1)/2; i < L; i++)
cntR[S[i]-'a']++
bool ret = true
for(c = 0; c < 26; c++)
if(cntL[c] != cntR[c])
ret = false
return ret
The time complexity for this is O(|S| + 26) per test-case.
Can be found here
Can be found here
I just made a free open source android app, Fridge for Codechef, which is my first big project. Basically, during long challenges, I wanted to read the questions whenever I got free time. So this app was born out of desire to solve long challenge questions, in an interface which is mobile friendly.
So, this app allows you to download all the questions from a contest or directly download any particular problem, which can then be viewed as per your requirement. You can easily share your favorite questions and contests, and search for them. This app can associate itself with codechef links to directly open them inside the app.
This is the very first release. Do leave your ratings, reviews, feedback, opinions and feature requests.
Hope you enjoy it!
Edit: Now android 4.4 support has been added so if you have a phone with android kitkat you can also download the app
Edit 2: Now you can set reminder for upcoming contests straight from the contests list
Also do not forget to rate and share the app, if you like it
Hello Guys, I'm back with another set of editorials in hope you would like them. :)
I hadn't attended December Cook Off due to certain unavoidable circumstances, that's the reason of no editorials for Cook Off.
Without wasting much time, Here are the editorials.
Given number of days in month and Day as on 1st of given month, Find out frequency of each day.
Simplest solution use if else statements (Carefully though).
For W = 28, print 4 for each day, because a month with 28 days will always have 4 Sunday, 4 Monday ans so on.
For W = 29, print 4 for all days except the day of first of month. Example, for input 29 mon, ans is 5 4 4 4 4 4 4. (frequency of monday increased by 1).
For W = 30, print 4 for all days except the day of first of month and its next day. Example, for input 29 mon, ans is 5 5 4 4 4 4 4. (frequency of monday increased by 1).
For W = 31, print 4 for all days except the day of first of month and next two days. Example, for input 29 mon, ans is 5 5 5 4 4 4 4. (frequency of monday increased by 1).
For proof of above, You may consult Calendar. :D
Link to my Code
Given A and N, compute $f(A^N)$, where $f(X)$ is defined as:
FIrst thing, make a function $f(X)$ as described above. Now, Notice that we need to calculate $f(ans)$ where ans = $A^N$, we can directly compute $f( (f(A))^N)$. Doing this avoids the issue of overflow.
Typical Modular exponentation Code (Refer geeksforgeeks) int power(int x, unsigned int y, int p) { int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1){
res = (res*x);
if(res>=p)res = res%p;
}
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
Now, our solution is similar to modular exponentation, with one change. In Modular exponentation, we take res = (res*x); if res >= p, res = res%p;
But in our solution, we take res = res*x; $if(res >= 10) res = f(res)$. This way, we are calculating $f(A^N)$ in the same manner as Modular exponentation.
That's all.
Reason this works, is that suppose we have A = 15, N = 2.
$f((9+6)^2) = f(6^2 + 9*(9+12)) = f(36 + 9*21)$
Now, notice that the term 9*21 will never affect the value of our function.
For further proof, Calculate $f(9*X + Y)$ for some values of X and Y. The answer will always be Y.
Link to my code
Given two bags of sweets with p and q sweets respectively, Find out number of ways of eating Exactly N sweets, subject to conditions that
Usually for counting problems where we need to make choices and count the number of ways of some sequence, we use DP, taking all the variables affecting answer in dp state.
DP state for this problem has been defined as
Base Case if(N == 0) return 1; if (N < 0, )return 0.
DP recurrence
if(last == 1)dp[N][p][q][B1][B2][last] = Summation from i = 1 to i = min(q,S2)solve(N-i, p,q-i,B1,B2-1, 2);
if(last == 2)dp[N][p][q][B1][B2][last] = Summation from i = 1 to i = min(p,S1)solve(N-i, p-i,q,B1-1,B2, 1);
Now, see what;s going on.
In each recursive call, we eat i sweets from bag other than the last one, Reducing sweets to be eaten, also reducing Number of sweets in that bag, and reducing the max number of times of opening respective bag by one, Thus, meeting all conditions.
Also, we run loop from 1 to min(p, S1) and 1 to min(q,S2), to comply with the condition of max sweets at a single step.
Also, use map in place of arrays which may give TLE. we do not visit all states.
Further We can also reduce state variables from 6 to 5 by noticing that N = P - p + Q - q where P and Q are input values while p and q is the current state values. But is didn't use it ad still it works. :)
Here's the link to my code.
Hope you all like my editorials.
On an important note, For further contests, One of my friend (@soham1234) has agreed to write unofficial editorials similar to mine. I hope you would like them too as much as you all do like mine.
Hi, I am getting tle for problem gss1.Can someone please help where I am going wrong. My code: https://ideone.com/BN5ecX Thanks.
Can anyone provide me links to some priority queue questions?
I am trying to understand this problem: Puchi and luggage. I understand that it is using Inversion Count of merge sort. But here, in author's solution, I don't understand why the Frequency array is updated twice where as it should be updated only once during merging..