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

help in bit manipulation question!


Programming Contest Detailed Syllabus Along with Example Problems

$
0
0

Competitive Programming Syllabus

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.

Geometry

String Algorithms

Substring search

Suffix Arrays

  • O(n^2 * logn) Naive method of suffix array construction
  • O(n * logn^2) method of suffix array construction
  • O(n * logn) method of suffix array construction
  • O(n) method of suffix array construction
  • O(n) LCA preprocess on Suffix Arrays to solve a variety of string problems

Suffix Trees

  • O(n) construction of Suffix trees using Ukkonon’s algorithm
  • O(n) construction of Suffix Trees if provided with Suffix Arrays using Farach's algorithm

Other

  • Suffix Automata - O(n) Suffix Automaton construction.
  • Dictionary Of Basic Factors - O(n * logn) method of DBF construction using Radix Sort.
  • Manacher’s algorithm to find length of palindromic substring of a string centered at a position for each position in the string. Runtime -> O(n).
  • Searching and preprocessing Regular Expressions consisting of '?' and '*'

Multi-dimensional pattern matching

Graphs

Basic Graphs

  • Representation of graphs as adjacency list, adjacency matrix, incidence matrix and edge list and uses of different representations in different scenarios
  • Breadth First Search (Problems - PPATH, ONEZERO, WATER on SPOJ)
  • Depth First Search
  • Strongly Connected Components (TOUR and BOTTOM on SPOJ)
  • Biconnected Components, Finding articulation points and bridges (RELINETS, PT07A on SPOJ)
  • Dijkstra algorithm (SHPATH on SPOJ)
  • Floyd Warshall algorithm (COURIER on SPOJ)
  • Minimum Spanning Tree (BLINNET on SPOJ)
  • Flood-fill algorithm
  • Topological sort
  • Bellman-Ford algorithm.
  • Euler Tour/Path (WORDS1 on SPOJ)
  • Suggested reading for most of the topics in Graph algorithms -http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=graphsDataStrucs1.
  • Also refer to the tutorial for problems concerning these techniques.
  • Cormen chapter 22 to 24.

Flow networks/ matching

Dynamic Programming.

Greedy

Number Theory

Modulus arithmetic

Fermat's theorem, Euler Totient theorem (totient function, order, primitive roots)

Chinese remainder theorem

Primality tests

GCD using euclidean method

Logarithmic Exponentiation

Integer Factorization

Other

Math (Probability, Counting, Game Theory, Group Theory, Generating functions, Permutation Cycles, Linear Algebra)

Probability

Counting

Special numbers

Advanced counting techniques - Polya counting, burnsides lemma

Game theory

Linear Algebra

Matrix Operations

Matrix transformations (Transpose, Rotation of Matrix, Representing Linear transformations using matrix)

Solving system of linear equations

Using matrix exponentiation to solve recurrences

Eigen values and Eigen vectors

Polynomials

Permutation cycles

  • Suggested Reading - Art of Computer Programming by Knuth Vol. 3
  • Problems - ShuffleMethod, Permutation and WordGame on topcoder.

Group Theory (Advanced Techniques)

Generating functions

  • Suggested Reading
  • Herbert Wilf's generating functionology
  • Robert Sedgewick and Flajoulet's Combinatorial analysis

Data Structures

Basic

Singly/Doubly Linked List

Hash Tables

Circular linked list / queue

Binary/n-ary trees

Heaps

Trie

Interval trees / Segment Trees

Fenwick (Binary Indexed) trees

Disjoint data structures

Range minimum Query (RMQ)

Customized interval/segment trees (Augmented DS)

AVL Trees

Miscellaneous

  • Splay Trees
  • B/B+ Trees
  • k-d Trees
  • Red-black Trees
  • Skip List
  • Binomial/ Fibonacci heaps

Exercices

Persistent Segment Tree

Centroid Decomposition

Heavy Light Decomposition

Search Techniques/Bruteforce writing techniques/Randomized algorithms.

Backtracking (beginner)

  • N queens problems
  • Knights Tour
  • Sudoku Problem
  • Tiling Problem
  • 15 puzzle.

Dancing Links and Algorithm X given by Knuth (advanced)

Binary Search (beginner)

Ternary Search (intermediate)

Meet in the middle (Intermediate)

Hill Climbing (Advanced)

Simulated Annealing (Advanced)

Regular Iteration to reach a fixed point (Advanced)

  • Newton-Raphson method to find root of a mathematical function.
  • Iterations to solve linear non homogeneous system of equations.

Representing sets with bitmasks and manipulating bitmasks (Beginner)

General programming issues in contests

References:

https://docs.google.com/document/d/1_dc3Ifg7Gg1LxhiqMMmE9UbTsXpdRiYh4pKILYG2eA4/edit1

AREAFIGR - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Praveen Dhinwa
Tester:Misha Chorniy
Editorialist:Animesh Fatehpuria

PROBLEM

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$.

EXPLANATION

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.

Solution One: Breaking into Rectangles

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.

Solution Two: Monte Carlo Based Simulation

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.

Solution three: Misha's deterministic solution

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 AND TESTER'S SOLUTIONS:

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

MANCBST - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Satyaki Upadhyay
Tester:Misha Chorniy
Editorialist:Animesh Fatehpuria

PROBLEM

Count number of semi-BSTs having exactly $n$ nodes. A semi-BST is a tree with $n$ nodes which satisfies the following conditions:

  • Each node contains a distinct value from $\{1, 2, 3, \dots, n\}$.
  • The root has at most two children.
  • The right subtree of the root (if it exists) is a valid semi-BST.
  • The left subtree of the root (if it exists) is any unordered rooted tree. That is, the children of a vertex are not ordered, and hence no concept of left or right child.
  • The BST property for the root is maintained, i.e. all the values in the left subtree of the root are lesser than that of the root and all the values in the right subtree of the root are greater than that of the root.

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$.

PREREQUISITES

Knowledge of "online" FFT trick.

EXPLANATION

We first solve the problem in $O(n^2)$, and then optimize it using a trick.

An $O(n^2)$ Solution

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)$.

Speedup using Online FFT

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 AND TESTER'S SOLUTIONS:

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

Discrepancy in Nov long

Help in Obtain Desired Expected Value

$
0
0

Can anyone tell me the approach of the third problem( Obtain Desired Expected Value ) of Chennai Onsite . Link of problem

Codechef Rating Predictor

$
0
0

Hello everyone!

alt text

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

  • 0 - 5868
  • 1 - 275
  • 2 - 125
  • 3 - 68
  • >= 4 - 55

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)

  • 0 - 5900
  • 1 - 485
  • >= 2 - 6

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

ABROADS - Editorial

$
0
0

Problem Link:

Practice
Contest

Difficulty:

Medium

Pre-requisites:

Disjoint Set Union

Problem:

Maintain the size of the most populated region after each query.

Explanation:

Solution for the subtask 1 (21 points):

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:

  • The number of the adjacent node, denoted by $node$.
  • The ID of the corresponding edge, denoted by $edge$.

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:

  • Add the first node of the region to the queue.
  • While the queue is not empty, pick the node from the head of the queue and add all its' not yet added neighbors.

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))$.

Solution for all subtasks:

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$).

Setter's Solution:

Can be found here

Tester's Solution:

Can be found here


Getting WA in BTAR

$
0
0

I did the exact same thing explained in the tutorial. It's passing the sample test cases but giving WA when submitted.Please help!

Problem

My solution

Will CodeChef provide test cases

$
0
0

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.

LECANDY - Editorial

$
0
0

PROBLEM LINKS:

Practice
Contest

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Basic knowledge of arrays and loops.

PROBLEM:

The program asks you to calculate if all the elephants would get the number of candies that they want.

EXPLANATION:

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).

SETTER'S SOLUTION:

Can be found here.

APPROACH:

The problem setter used the above solution to solve the problem.

TESTER'S SOLUTION:

Can be found here.

APPROACH:

The problem tester used the above solution to solve the problem.

How do I win a CodeChef Goodie?

$
0
0

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?

ALPHABET - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Sergey Kulik
Tester:Harshil Shah
Editorialist:Pawel Kacprzak

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Strings, Implementation

PROBLEM:

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.

QUICK EXPLANATION:

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.

EXPLANATION:

Subtask 1


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.

Subtask 2


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.

AUTHOR'S AND TESTER'S SOLUTIONS:


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

CS Academy Special Round #64 (Interactive only) with Prizes

$
0
0

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!

LAPIN - Editorial

$
0
0

Problem Link:

Practice
Contest

Difficulty:

Cakewalk

Pre-requisites:

ad-hoc

Problem:

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.

Explanation:

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.

Setter's Solution:

Can be found here

Tester's Solution:

Can be found here


Android app for codechef with offline support

$
0
0

Fridge for Codechef

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

Play badge

Unofficial Editorials December Lunchtime

$
0
0

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.

Days in a Month

Difficulty: Cakewalk

Problem:

Given number of days in month and Day as on 1st of given month, Find out frequency of each day.

Solution:

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

Strange Function

Difficulty:Easy

Problem:

Given A and N, compute $f(A^N)$, where $f(X)$ is defined as:

  • Compute the sum of digits of A; let's denote this sum by S.
  • If S is a single-digit integer, then F(A) = S.
  • Otherwise, F(A) = F(S).

Solution:

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

Too Much Sweetness

Difficulty: Easy-medium

Prerequisites: DP

Problem

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

  1. ith bag cannot be opened more than Bi time.
  2. We cannot eat more than Si sweets in one step from ith bag.
  3. We need to choose bags alternatively.
  4. First bag can be either one.

Solution;

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

  1. N = Number of sweets to be eaten.
  2. p = Number of sweets in Bag 1
  3. q = Number of sweets in Bag 2
  4. B1 = Number of times we can open Bag 1
  5. B2 = Number of times we can open Bag 2

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.

spoj gss1 tle

Priority Queue Questions !!!

$
0
0

Can anyone provide me links to some priority queue questions?

Help with Puchi and Luggage

$
0
0

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..

Viewing all 40121 articles
Browse latest View live


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