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

PRCN16A - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Editorialist:Rounaq Jhunjhunu Wala

DIFFICULTY:

EASY

PREREQUISITES:

Factors

PROBLEM:

Given a number $N$, we need to find the sum of all factors of $N$.

EXPLANATION:

This is a very common problem of number theory. The easiest approach to this is to simply loop from 1 to $N$ and add all the numbers which are the factors of N.

ans = 0
for i = 1 to N
  if N%i == 0
    ans = ans + i
print ans

The above approach works, but it is $O(N)$, so it will give a TLE result. We can do the same in $O(\sqrt{N})$ time complexity.
We know that for any factor $i$ of $N$, there is a corresponding factor $\frac{N}{i}$ (if $i \neq \sqrt{N}$). Now, if we take the smaller of $\{i,\frac{N}{i}\}$, the value would be atmost $\lfloor{\sqrt{N}}\rfloor$, because if both factors are greater than this quantity, then their product is greater than $N$, which is not possible.
The observation above gives us the required algorithm:

ans = 0
for i = 1 until i*i <= N
  if N%i == 0
    ans = ans + i
    if i != N/i:
      ans = ans + N/i
print ans

The if check is to handle the case when we get $i$ as the perfect square root of $N$, in which case only $i$ should be added.


CHN15B - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Arjun Arul
Tester:Kevin Atienza
Editorialist:Kevin Atienza

DIFFICULTY:

Easy

PREREQUISITES:

Expected value

PROBLEM:

There are $N$ coders numbered $0\ldots N-1$ and ordered according to ratings. Each coder $i$, except the first, selects a person $\text{choice}[i]$ with a higher rating to be teammates with, or $-1$ if the coder is lazy. (Thus, $-1 \le \text{choice}[i] < i$.) The first person has $\text{choice}$ equal to $-1$ even though he/she is not lazy.

For each lazy person $i$, $\text{choice}[i]$ is replaced with a uniformly random value from $0$ to $i-1$ with $1/2$ probability.

What is the expected value of the number of teams?

QUICK EXPLANATION:

The resulting graph will always be a forest, no matter what. Also, a forest with $N$ nodes and $E$ edges has exactly $N-E$ components. Thus, the answer is $N$ minus the expected number of edges.

Let $L$ be the number of lazy people. Each lazy person has a $1/2$ probability of having $\text{choice}[i]$ be replaced, so by linearity of expectation, the expected number of edges across all lazy people is $L/2$, and the expected number of edges overall is $L/2 + (N-1-L)$. Thus, the answer is $N - (L/2 + (N-1-L))$, or $1 + L/2$.

EXPLANATION:

Let's imagine setting the $\text{choice}[i]$ of each lazy person $i$ one by one. At any point in time, the coders form a bunch of teams, and after each update, two of these teams may merge, so the number of teams may increase by one. However, it's possible that the number of teams doesn't increase, in case $i$ and $\text{choice}[i]$ were already teammates to begin with. Now, when does this exactly happen?

Suppose we want to set $\text{choice}[i]$ to some value $j \in [0,i)$. Now, consider a path from $j$ to $i$. Naturally, this sequence of nodes will sometimes decrease and sometimes increase. However, it's impossible for the sequence to increase and then decrease, because that would mean that some person had two $\text{choice}$ values. More specifically, remember that the only way for $j < i$ to be connected by an edge is when $\text{choice}[i] = j$, which means that if the sequence went $a < b > c$, then $\text{choice}[b] = a$ and $\text{choice}[b] = c$, which is absurd.

This only means that the sequence can only decrease, and then increase until it reaches $i$. But this means that the node $j'$ right before $i$ in the path is $< i$ and adjacent to $i$, thus $\text{choice}[i] = j'$, contradicting the fact that $i$ is lazy. All of this means that it's impossible to choose any $\text{choice}[i]$ in such a way that will connect two people that are already teammates, in other words, form a cycle in the graph. In other words, the graph is always acyclic!

An undirected graph with no cycles is called a forest, and it's easy to prove some elementary facts about forests. The following fact will be most useful for us:

In a forest of $N$ nodes and $E$ edges, the number of connected components is $N - E$.

This is easily proven by induction, and is actually pretty intuitive. I suggest drawing out a few random forests to get some intuition behind this.

In our case, each team corresponds to a connected component, so the number of teams is $N - E$. The expected number of teams is therefore equal to the expected value of $N - E$, which, by linearity of expected values, is equal to the expected value of $N$ minus the expected value of $E$. Now $N$ is constant throughout the whole procedure, which means we only need to compute the expected value of $E$.

Now we're getting closer to the solution. Let $L$ be the number of lazy people. Thus, there are $N - L$ non-lazy people, and there are already $N - 1 - L$ edges in place. (Remember that $\text{choice}[0] = -1$.) Now, let $i_1, i_2, \ldots, i_L$ be the indices of the lazy people. We define $L$ new random variables $X_1, X_2, \ldots, X_L$, where $X_k$ is $1$ if the coin lands tails for person $i_k$ (thus $\text{choice}[i_k] \not= -1$), and $0$ otherwise. Using the $X_k$s, we can now express the number of edges in the graph after the procedure: $$(N - 1 - L) + X_1 + X_2 + X_3 + \ldots + X_L$$ But we want the expected value of this thing. Easy! By linearity of expected values again, this is simply equal to: $$(N - 1 - L) + E[X_1] + E[X_2] + E[X_3] + \ldots + E[X_L]$$ Now, we focus on $E[X_k]$. We know that there is $1/2$ probability that $X_k = 1$, and $1/2$ probability that $X_k = 0$. Thus, the expected value of $X_k$ is simply $1/2$. This applies to all other $k$s, thus the expression above is simply: $$(N - 1 - L) + 1/2 + 1/2 + 1/2 + \ldots + 1/2 = N - 1 - L + L/2 = N - 1 - L/2$$ Finally, the expected number teams is: $$N - (N - 1 - L/2) = 1 + L/2$$ which is a neat answer. Notice that we didn't really care which people are lazy. We only need the number of lazy people!

Time Complexity:

$O(N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

AVGSHORT - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

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

DIFFICULTY:

EASY-MEDIUM

PREREQUISITES:

Graphs, shortest paths, binary search, Bellman-Ford algorithm

PROBLEM:

For a given nodes A and B, find the average length of a walk between A and B that has the smallest average length among all such walks or decide that there is no walk between these nodes.

QUICK EXPLANATION:

First, check if B is reachable from A. If not, we are done. Otherwise, perform a binary search over all possible resulting average lengths. For a fixed average length L, use Bellman-Ford algorithm to find out if the graph has a walk from A to B with average length less or equal to L.

EXPLANATION:

Subtask 1

In the first subtask the constraints are very small, we have at most 10 vertices and at most 20 edges. One may try various approach within these constrains. One of them may be to first find out average lengths of all simple paths from A to B by examining all of them, and after that, try to form an infinite walk between A and B by adding a cycle with some minimum length L, which when the walk is infinite, will dominate other length is such a path. Alternatively, some approximate solutions may be also possible, because the required precision of the answer in this subtask is not very restrictive.

Subtask 2

Let’s assume that B is reachable from A, because in the other case the answer is obvious, and this can be easily check by a simple DFS. After that, let’s try to solve a different problem:

For a given value L, decide if there exists a walk from A to B with average length not greater than L.

How is this problem simpler than the original one? Well, let’s assume that there exists a walk W from A to B with average length less or equal to L. Now, let’s subtract L from all weights of edges in the graph. How does this operation affect W? Since its average length was not greater than L before, and we subtracted L from all weights, now its absolute length is not greater than 0. Moreover, this operation of lowering weights of edges affects all paths in the same way, i.e. the relative order of their average lengths is not affected by the operation (be careful here, this is not true when operating on absolute lengths instead of average lengths).

So far so good, but how to find out if there is a walk from A to B of length not greater than 0? It is very important that we are looking for a walk, not only for a simple path here. Moreover, after subtraction, weights on edges can be negative, which is also important for certain algorithms to work. Fortunately, Bellman-Ford algorithm can be used here. It works perfectly with negative edges and can be used to detect if a graph has a negative length cycle, which is crucial in the solution.

In order to find out if there is a walk from A to B with length not greater than 0, we run Bellman-Ford algorithm to compute the shortest simple path from A to B. If its length is not greater than 0, we are done. Otherwise, we use Bellman-Ford to check if there is a negative length cycle C in the graph, with the property that C is reachable from A and B is reachable from C. If there is any such cycle C, then by traversing it enough number of times, we can always lower the cost of the path (which is in fact a walk right now) to be not greater than 0. If there is no such cycle, then there is no walk from A to B with length not greater than 0, because there is no such simple path between them with that property and there is no negative cycle which can lower a cost of any path from A to B. This solution works in O(N * M) time, because this is the running time of Bellman-Ford algorithm. Thus in this time we can solve the problem of deciding for a fixed value L if the graph has a walk from A to B with average length not greater than L. How to use this fact to solve the original problem? Well, we can use binary search over all possible values of L, and for a fixed value of L we can solve the problem described above. Notice that since all weights of edges in the graph are within a range [1, 100], all possible values of L are also within this range. Moreover, since the required precision of the answer is to return it with absolute or relative error not greater than 10-6, we can stop binary search as soon as the range of valid values of L is reduced enough to fulfill this requirement. For more details please refer to author’s and tester’s solutions.

AUTHOR'S AND TESTER'S SOLUTIONS:


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

Hackerearth Dp problem

REVENG04 - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Akshat Jain
Tester:Ankit Kathuria
Editorialist:Akshat Jain

DIFFICULTY:

MEDIUM

PREREQUISITES:

Interest in Coding, Strings.

PROBLEM:

Finding the problem is the first task based on the input, output format and exe file provided. Then think the logic and code the same.

QUICK EXPLANATION:

The task in this problem is to find the alphabets which are present only in one word among the input paragraph string.

EXPLANATION:

• The first input is the number of test cases.

• The next line contain a string paragraph i.e. space separated small case letters.

• We may use a matrix with 10000 rows and 26 column, each row representing a word from string and columns representing the alphabets present in each word.

• Now we may count the occurrence of each alphabet in different words(repetitions in same word are ignored), this may be done by simply adding up all the rows(columnwise).

• If the addition comes out to be exactly one then it has to be displayed, else not.

• Finally all the alphabets must be displayed in alphabetical order and NONE if no such alphabet is found.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

GOVT - EDITORIAL

$
0
0

Problem Links

Practice
Contest

Author: Ankur Goel

Tester: Ankur Goel

Editorialist: Ankur Goel

Difficulty

Medium

Prerequisites

Factorial

Problem

In a secret government project there are N investors who can invest X1,X2.........XN amount in millions such that X1,X2.........XN are all distinct i.e the amount they are ready to invest are different and the amount is not in fraction (i.e example X1= 1 million is valid but X1=1.5 million is invalid).There is a policy for forming groups among investors.Two investors who are ready to invest (suppose X1 and X2 amount individually) when grouped together,they feel confident and wish to invest more such that their total invested amount is equal to the sum of product of their individual investments added to their individual amount to be invested(i.e individually they could invest X1 and X2 amounts but after grouping together they can invest a total amount of X1+X2+X1*X2).Investors can further be combined with other investors and groups but by using the grouping policy mentioned before.
The Target is to find the maximum amount of money the government can fetch from the n investors.

Quick Explanation

Ans= (Factorial(N+1)-1)%M

Explanation

The Problem is simply based on the Factorial. Lets have a close look at this problem by with the help of an example.Let N=3, and X1=1, X2=2 and X3=3. It does not matter which two of the investors should be grouped at any point of time because whichever two you group at any time, the final answer will be same.
Let us first group X1 and X2
=> X(1,2)=1+2+1*2=5
Now Lets group X(1,2) and X3
=> X(X(1,2),3) = X(5,3) = 5+3+5*3= 23 = Factorial(4)-1
In General for n investors, Ans= (Factorial(n+1)-1)%M
Use 64 bit int and take modulo at every step in calculating factorial to prevent the overflow.

Author's Solution

Author's solution can be found here

Related Problems

Primorial

FICE - Editorial

$
0
0

Problem Links

Practice
Contest

Author: Ankur Goel

Tester: Ankur Goel

Editorialist: Ankur Goel

Difficulty

Medium

Prerequisites

Fibonacci Series, Recursion

Problem

The King wants to select N common folks as solider from the Fire and Ice island in order to win the battle. He can only select odd number of people from land of fire or ice only in one go.He cannot select bunch of people consecutively from either territory.Find the number of ways the mad king could select his army.

Note :The number of people in each territory is infinite.

Quick Explanation

Ans= 2*Fibo(N)%M

Explanation

The Problem is simply based on the Fibonacci Series. Let 0 denotes the people from Land of Ice and 1 denotes the people from Land of Fire then, the number of binary strings of length n without an even number of consecutive 0s or 1s is 2Fn. For example, out of the 16 binary strings of length 4, there are 2F4 = 6 without an even number of consecutive 0s or 1s – they are 0001, 0111, 0101, 1000, 1010, 1110.

Find the Fibonacci using O(Log N) Algorithm and take the modulo M at every step, otherwise your algo may fail due to Time Complexity or due to the Overflow of Fibonacci Number beyond the range of even 64 bit int.

Author's Solution

Author's solution can be found here

Related Problems

Ankur and Coins

LUFFY - Editorial

$
0
0

PROBLEM LINK:

Contest
Mirror
Practice

Author: Rupesh Maity
Tester: Asim Krishna Prasad
Editorialist: Rupesh Maity

DIFFICULTY:

Medium

PREREQUISITES:

DFS, Point in Polygon

PROBLEM:

Given N circles and a point in 2D plane. Check if the point is completely surrounded by circles or not, i.e., if there is a way out.

QUICK EXPLANATION:

Check if the point (x, y) lies inside any of the given circles, then he is trapped. Join the centres of the circles which intersect and consider them as edges. We now have a graph. The point (x, y) is considered trapped only if it lies inside any of the cycles in this graph formed. Find a ray passing through the point (x,y) and not passing thourgh any of the vertices of the graph. Assign the value 1 to all the edges that intersect this ray and 0 to all the other edges. If there are any odd cycles in the graph, the answer is "YES".

EXPLANATION:

Check if the point (x,y) lies inside any of the given cirlces and print "NO" if it does. Notice that, we cannot pass between two circles if they are intersecting. Thus, we can construct an edge between the centres of these 2 circles representing that you cannot pass through this edge. We check this for every pair of circles given in our input. This can be done in O(N^2), where N is the number of circles. After we're done constructing all the edges, we now have a graph. The problem now comes down to finding if the given point lies inside any of the cycles formed by this graph.

Now let's only concentrate on the graph and the point. We know that, if a point lies inside a polygon, all the rays emerging from this point intersect the polygon exactly odd number of times. Using this property of a "Point in a polygon", we try to find a ray (a line emerging from point (x, y)) which does not pass through any of the vertices of our graph. We are doing this because we want to avoid any complex case that may arise due to the ray passing through a vertex. We need to find a point (x1, y1), such that a ray starting at (x, y) and passing through (x1, y1) does not pass through any of the vertices. One way to do it is by taking (x + 1, 10^5) as (x1, y1). This is because, no vertex in input can lie on the line (x, y) and (x + 1, 10^5), as (xi, yi <= 10^4). I did it differently by fixing x1 = x + 1 and iterating over a few values of y1 until I found a point satisfying my condition.

Now, lets mark all the edges passing through this ray as weight 1 and the rest of the edges as weight 0. Now the problem comes down to finding any cycle in the graph which has odd weight. This can be done by a simple DFS, keeping note of the total weight encountered until now and checking for any odd weighted cycles in the traversal.

Time Complexity: O(N^2)

Author's Solution:

Author's solution can be found here.


DIAGON - Editorial

$
0
0

PROBLEM LINK:

Contest
Mirror
Practice

Author: Rupesh Maity
Tester: Asim Krishna Prasad and Sarvesh Mahajan
Editorialist: Rupesh Maity

DIFFICULTY:

EASY

PROBLEM:

Given a sorted array of distances to visit and a few dependencies (right to left) on the order of visit and the final destination point, find the minimum distance required to cover all the array elements and finally reach the end point.

EXPLANATION:

Since the dependencies are from right to left, visiting all the shops in the way to the rightmost shop, then returning back to the leftmost non-visited shop and then going to the destination shop will surely cover all the shops. Notice that, you will have to pass through every shop atleast once and atmost thrice. So now, you have the general idea of how we are supposed to visit these shops.

We start by going right. We know that, if there is a non-visited shop towards the left, we will surely have to go back once to visit it. Why not save this back traversal until all the dependencies to your left have already been covered. That is, suppose there are dependencies (5, 9) and (7, 11), going from visiting the shops in this sequence (9, 5, 11, 7), will cover a total distance of (9+4+6+4 = 23), whereas visiting in this sequence (9, 11, 7, 5) gives us a total distance of (9+2+4+2 = 17). You see what we have done there, since '7' is an unvisited shop but its dependency '11' has not been visited yet, we dont want to go to 5, we can go back to 5 once the dependencies (remember, 7 can have more than one dependency) for 7 have been visited. So in short, what we are doing is just merging the intervals to form the smallest intervals which do not have any other dependency outside this interval.

For example, suppose we have dependencies (1, 7), (5, 8), (10, 11), the merged intervals will be (1, 8) and (10, 11). This can be visited in this order (8, 1, 11, 10) giving an answer (8+7+10+1=26). You might be wondering that, if we had visited in this order (8, 11, 10, 1), the total distance would have been equal to 21. I am explaining how we are merging the intervals. There may still be shops to the right which might need to be covered. That is, if the rightmost shop to be covered is at 20, then the order (8, 1, 11, 10, 20 = 36) gives a better answer than (8, 11, 10, 1, 20 = 40). Read the below part to understand how this plays an important role.

The only case left to be considered is the final shop to be visited (ice-cream shop given in the question). This shop is supposed to be visited last. If this shop is located after the rightmost shop, we can just directly visit it after visiting all other shops. But if it is located in between, we know that, we have to make a back traversal at the very end. Now, in the same way we saved this back traversal previously (as discussed earlier), we can do the same here. In the example above, suppose the goal is at 5, it doesn't make sence to visit (8,1,11,10,5) giving total distance = 31. Instead, if we go in this order (8, 11, 10, 1, 5), we get a total distance = 25.

If you were not able to solve this question and are reading this editorial for hint, either the idea of visiting back to the left 'only once' has probably not striked you yet or you are handing the case of visiting the ice-cream shop differently. Think over it. Comment your queries below if you're still facing problems.

Complexity: O(N)

Author's Solution:

Author's solution can be found here.

BOBPRIME - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Sarvesh Mahajan
Tester:Sai Sandeep

DIFFICULTY:

MEDIUM-HARD

PREREQUISITES:

Inclusion-Exclusion,Mobius Function,Binary search

PROBLEM:

Define degree of a number is the highest power of a prime in its prime factorisation. A bob-prime is a number having prime degree. Find kth smallest bob-prime.

QUICK EXPLANATION:

Binary search for the answer. Denote f(x,deg) as the number of numbers <= x , having degree >= deg. f(x,deg) can be found using inclusion-exlusion or mobius function.

EXPLANATION:

Let's convert the problem into a counting problem. Finding kth bob-prime is same as finding the first x such that there as less than or equal to k bob-primes less than it. Therefore, we can do a binary search for this x and the problem turns into finding the number of bob-primes less than a given number. The problem constraints guarantee that the answer is always < $10^{10}$. So this can be the upper limit for the binary search.
Let's say we have a function g(x,deg) which returns the number of numbers<=x having degree=deg. Then we can use the following pseudo-code to calculate the answer.

def get(x): # Returns number of bob-primes<=x for(p in primes): ret+=g(x,p) return ret

Note that we only need to iterate till primes<37 since 237> 1010. Now the problem remains how to calculate g(x,deg).

Calculating g(x,deg):

Let f(x,deg) return the number of numbers<=x having degree>=deg.
Then clearly g(x,deg)=f(x,deg+1)-f(x,deg).
f(x,deg) can be calculated by inclusion exclusion. We add the count of numbers<=x divisible by ${2^{deg}},{3^{deg}},{5^{deg}},{7^{deg}} $ and so on. But we are overcounting here. So we subtract the count of numbers<=x divisible by ${2^{deg}}{3^{deg}} etc.$

Therefore, f(x,deg)= $\lfloor{\frac{x}{2^{deg}}}\rfloor + \lfloor{\frac{x}{3^{deg}}}\rfloor + \lfloor{\frac{x}{5^{deg}}}\rfloor + ...- \lfloor{\frac{x}{2^{deg}3^{deg}}}\rfloor-\lfloor{\frac{x}{2^{deg}5^{deg}}}\rfloor- .... + \lfloor{\frac{x}{2^{deg}3^{deg}5^{deg}}}\rfloor... $

Note that the denominator grows very fast so the number of non-zero terms is relatively small. Also note that since deg>=2, we only need to consider primes till $10^{5}$, as any number greater than this will contribute only a zero term in the answer.

Implementation details

We can calculate all prime numbers <= $10^{5}$ using sieve of Erastothenes.
We can generate the terms in denominator using recursion and prune the recursion tree by stopping when the denominator exceeds x. Also pre-compute values of prime powers<37. Refer author's solution for details.

Alternatively, if you are familiar with mobius function, you will notice that this inclusion-exclusion is implicit in the definition of mobius function. We can calculate the values of mobius function for all numbers <=$10^{5}$ and then,
f(x,deg)= $ - \sum_{y=2}^{10^{5}} \mu (y) *(x/y^{deg})$.
For details regarding calculation of mobius function refer tester's solution.
Time Complexity: Let max denote the bob-prime corresponding to the largest value of k. Then time complexity is $O(T*log(max)*sqrt(max))$

AUTHOR'S AND TESTER'S SOLUTIONS:

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

TREE02 - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Sai SandeepTester:Aditya Shah

DIFFICULTY:

MEDIUM

PREREQUISITES:

Binary Search, Depth First Search

PROBLEM:

Given a tree with weights on vertices, and $k$, Find the minimum value of the maximum weight of subtree that can be obtained by partitioning the tree into $k$ parts.

QUICK EXPLANATION:

Binary search the answer.

EXPLANATION:

We will first check for a given $x$, if we can partition the tree into $k$ parts such that each part is less than or equal to $x$, and then binary search the answer.

Let's root the tree at node 1. Say a subtree rooted at vertex $v$ has weight <= $x$, there exists a cut in which no edge inside the subtree is used. This is because, we can replace that edge with the edge between $v$ and it's parent, the cut still satisfies the condition that all the subtrees have weight <= $x$

What if subtree rooted at $v$ has weight > $x$ and all the subtrees rooted at it's children have weight <= $x$ ? From our first observation, we have to cut some edges connecting $v$ and it's children. But which edges to cut ? Say we cut $i$ of these edges, but we can cut the $i$ edges such that the weights of subtrees that we cut is maximum, the condition still holds. So we should cut the subtees with large weights and we should cut as less as possible. Thus, we start from the least weight one and start adding up weights till the weight is <= $x$, once the total weight crosses $x$, we are forced to cut all the rest.

This gives a recursive algorithm to check if we can maintain all the subtree weights <= $x$. We run the previous algorithm and find the number of cuts required. If it's >= $k$, then that $x$ is not valid. By binary search, we find the smallest $x$ that is valid.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

HIKARU - Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Sai SandeepTester:Aditya Shah

DIFFICULTY:

HARD

PREREQUISITES:

Network Flows

PROBLEM:

Given sum of degrees of each vertex of graph, check if such a weighted graph can exist, if the upper bound on weight of edge between vertices i and j is i^j ( Bitwise xor )

QUICK EXPLANATION:

Check if the sum of degrees is even.

Construct a flow network with N vertices on left and right, edge with capacity i ^ j from i th vertex on left to jth vertex on right. Add a source and sink, with capacities equal to sum of degrees of vertices on left and right. Check if the flow equals the sum of degrees.

EXPLANATION:

First of all, the sum of degrees of the graph is even. See this

From here onwards, we use $c_{ij}$ to denote i^j, $d_i$ to denote sum of degrees of i. Lets construct a flow network, with N vertices on left and N vertices on right, edge of capacity $c_{ij}$ from i on left to j on right. Add a source on left and edges of capacity $d_i$ from source to i on left. Add a sink on right and edges of capacity $d_i$ from i on right to sink.

Suppose that there is such a graph satisfying the conditions in the problem, then the maximum flow in this graph is equal to sum of $d_i$, since we can send $w_{ij}$ on the edge between i on left and j on right.

Is the converse true ? Why can't it possibly not hold ? It's because in our flow network, $e_{ij}$ and $e_{ji}$ need not be same. But we can still consider $w_{ij} = (e_{ij} + e_{ji} )/2$ and it will satisfy the sum of degrees criterion. But the problem with this is that we no longer have integral weights on the edges. It can be a fraction, but still integral multiple of 1/2.

It turns out that if the sum of degrees is even, this flow can be modified to get a flow in which we don't have these non-integral weights. For example, if there is an even cycle with non-integral weights, we can add 1/2 to alternate edges and subtract 1/2 from rest to get rid of these non-integral weights. If we have two odd cycles with non-integral flows, we can adjust the flow from one cycle to other to get rid of all the non-integral ones. See this writeup for more formal proof.

Of course, we need not code all that, we just need to check that sum of degrees is even. But to arrive at that, we need above observations.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

ASYA2 - Editorial

$
0
0

PROBLEM LINK :

Contest
Practice

Author : Asim Krishna Prasad
Tester : Sarvesh Mahajan

DIFFICULTY :

CAKEWALK

PREREQUISITES :

Bitwise operations

PROBLEM :

Given two sets of strings A and B, you have to find how many such pairs (Ai, Bj) exist such that concatenation of the two strings contains all the letters of English alphabet.

EXPLANATION :

First there are a few observations :

  • We don't need the whole string for computation. We just need to know if a particular alphabet is present in a particular string or not.
  • Since we can loop over A x B, we only need a fast method to represent and concatenate two representations of strings

To solve this problem we can use bits to map if a particular alphabet is present in a string or not. So,

  • A string will be represented as an integer value which has bits set corresponding to each distinct alphabet present in the string. Example : for string A : 1, for string AC : 5 = (101)2.
  • Now concatenation of two strings would be equivalent to taking bitwise-or of the corresponding integers. That is, if either one of the strings has a bit set, it would be set in the concatenated string.

To make the integer corresponding to a string :

int inLimit = strlen(str1);
int num = 0;

fl(j,0,inLimit)
{
    int ele = int(str1[j]-'A');
    num |= (1 << ele);
}

Now the answer is the number of pairs (Ai Bj) such that bitwise-or of them has 26 set bits from beginning or bitwise-or has value equal to ( (1 << 26) - 1).

SOLUTION :

Setter's solution

INSQ16D - Editorial

$
0
0

PROBLEM LINK :

Contest
Practice

Author : Asim Krishna Prasad
Tester : Manish Kumar Sinha

DIFFICULTY :

EASY - MEDIUM

PREREQUISITES :

Probability, Dynamic Programming, Maths.

PROBLEM :

Given total number of Pokemons, number of distinct Pokemons Asya can make happy on a single day and number of days for which Asya visits Pokeworld, you are asked to calculate the probability of exactly Q number of distinct Pokemons being happy after D days.

Note that Asya can meet the same Pokemon on different days

EXPLANATION :

Each test case can be modeled in a dynamic programming problem. The states of DP would be, Day and DistinctPokemonsMadeHappySoFar.

The base case would be, when we reach the Dth Day, we need to check if we have DistinctPokemonsMadeHappySoFar equal to given Q.

If it is true, probability is 1.0 or else 0.0.

Tricky part is the transition from a state as Asya can meet the same Pokemon on different days.

Let us say we are on state (Day, DistinctPokemonsMadeHappySoFar). From this state what are all the possible sates we can jump to?

On this state, we can divide the total number of Pokemons into two sets, DistinctPokemonsMadeHappySoFar and PokemonsNotHAppySoFar.

Now we have to choose exactly A number of Pokemons from these two sets (combined). What we can do is, take zero Pokemons from 1st set and remaining from 2nd set or take 1 Pokemon from 1st set and remaining from 2nd set and so on. The probability for each of these selections gets added up.

What is the probability of each selection?

Well, if our recurrence function is rec(Day, DistinctPokemonsMadeHappySoFar), then :

(
C[DistinctPokemonsMadeHappySoFar][A - i]
* C[P - DistinctPokemonsMadeHappySoFar][i]
* rec(Days + 1, DistinctPokemonsMadeHappySoFar + i)
) / C[P][A]

where i is the number of new Pokemons Asya meets on this day, and i ranges from 0 to A inclusive.

We can pre - process the C[][] matrix.

Complexity of this solution is O(D * P * A) for every test case, that is : 31250 iterations per test case.

Since there can be 100 test cases, so 31250 x 100 = 3.125 x 10 6 which is acceptable.

SOLUTION :

Setter's solution

CIRCLEQ - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author: amrmahmoud
Tester: dpraveen
Editorialist: tsreaper

DIFFICULTY:

Medium-Hard

PREREQUISITES:

BIT/Fenwick Tree, Geometry

PROBLEM:

Given $N$ circles. No two circles touch or intersect each other. Given $Q$ queries. Each query is a rectangle. Calculate the total area of the circles within the rectangle.

EXPLANATION:

Let $ans(x_1,y_1,x_2,y_2)$ be the answer of the rectangle whose left-down corner is $(x_1,y_1)$ and right-up corner is $(x_2,y_2)$, it's obvious that:

$ans(x_1,y_1,x_2,y_2)=ans(0,0,x_2,y_2)-ans(0,0,x_1,y_2)-ans(0,0,x_2,y_1)+ans(0,0,x_1,y_1)$

So we can divide one query into four queries, now what we need to focus on is the total area of the circles within the rectangle whose left-down corner is $(0,0)$ and whose right-up corner is $(x',y')$.

Let's define the right-up point of a circle whose center is $(x_0,y_0)$ and whose radius is $r$ as $(x_0+r,y_0+r)$. For each rectangle we need to calculate, there are 3 kinds of circles.

cc-circleq.png

1) The right-up point of the circle is in the green rectangular area, so the whole circle is within the $(0,0,x,y)$ rectangle. To solve this part of the problem, we need to sum up all the areas of the circle whose right-up point is in the green rectangular area. This is a classic two dimensional partial order problem which can be solved using BIT/Fenwick tree.

2) The right-up point of the circle is in the red rectangular area, so the straight line $x=x'$ or $y=y'$ goes through the circle and divide it into two halves. For a circle whose radius is $r$, there are at most $4r$ lines which go through the circle. For each line, we can pre-calculate which circles it goes through. Then for each query, we can use binary search to find the right most circle which $x=x'$ goes through and whose right-up point is in the red rectangular area and sum up the areas. We can do the same thing for $y=y'$.

3) The right-up point of the circle is in the blue rectangular area. Note that no two circles touch or intersect each other, so for a fixed radius $r$, there are at most 2 circles whose right-up point is in the blue rectangular area. So we can loop through all $r$, and calculate the areas directly.

Sum all the three kinds of areas up, and we get the answer.

TIME COMPLEXITY:

For the first kind of circle, the time complexity is $O((N+Q)logX)$, where $X=50000$.

For the second kind of circle, the time complexity is $O(NR+XlogX+QlogX)$, where $X=50000$ and $R=50$.

For the third kind of circle, the time complexity is $O(QR)$, where $R=50$.

MY SOLUTION:

My solution

(Sorry for the poor English.)


BUG2K16C - Editorial

$
0
0

PROBLEM LINK:

Contest

Author: Rishabh Karnad
Tester: Omkar Prabhu
Editorialist: Rishabh Karnad


DIFFICULTY:

Easy


PRE-REQUISITES:

Dynamic Programming


PROBLEM:

Given a rectangular grid of dimensions m x n, in which each cell consists of either a 1 or a 0, find out whether there exists a path from (m,0) to (0,n) which only passes through cells containing 1s, while only making the following moves:

  1. (i,j) -> (i-1,j) [An UP or NORTH move]
  2. (i,j) -> (i,j+1) [A RIGHT or EAST move]


SOLUTION:

This problem has a typical dynamic programming solution.

The grid itself is represented as a matrix, say grid[m][n], whose contents are 0s and 1s and taken as input. A second matrix, say path_exists[m][n] is used to contain the information about the existence of a path to every cell; if path_exists[i][j] is 1, then there is a path from (m,0) to (i,j) and if it is 0, there is no path to (i,j).

The algorithm begins at (m,0) and may proceed row-by-row, column-by-column or diagonal-wise. For simplicity, we consider a row-by-row approach. Two loops are required: an inner j loop for columns and an outer i loop for rows. For each cell (i,j), we check if:

  1. Either or both path_exists[i+1][j] and path_exists[i][j-1] is 1. If yes, it means a path exists to one of those cells (i+1,j) or (i,j-1).
  2. grid[i][j] is 1, meaning that a path can pass through it.

If both conditions are satisfied, then the path to (i+1,j) or (i,j-1) can be extended to (i,j). Hence a path to (i,j) exists and we mark path_exists[i][j] as 1. Otherwise, we mark it 0.

When the algorithm terminates, the value of path_exists[0][n] will indicate the existence of a path between (m,0) and (0,n).


TIME COMPLEXITY:

Since each cell must be checked and operation on each cell takes constant time, time complexity is O(n^2).


SPACE COMPLEXITY:

O(n^2)
It can be reduced to O(n) by keeping track of only two rows at a time in path_exists and the algorithm can still be made to work correctly.


AUTHOR'S SOLUTION

Will be provided soon.

CDQU5 - Editorial

$
0
0

PROBLEM LINKS:

Practice
Contest

Author:Animesh Fatehpuria
Testers:Rajat DeSumit Shyamsukha
Editorialist:Animesh Fatehpuria

DIFFICULTY:

SIMPLE

PREREQUISITES:

Combinatorics , DP.

PROBLEM:

Given a number X , output the total number of ways one can score a score of X by hitting only Cannon and In-Off shots. A cannon shot gives 2 points and an In-Off shot gives 3 points.
Since the answer can be very large, Output the answer MOD 1000000009(10^9+9)

EXPLANATION:

The best way to approach this problem would be through DP and by using memoization.
Before we talk about that , let's look at a naive recursive approach:

Let us define a function f(x) which represents Number Of Ways to get a Score Of X.

The Important observation is:

f(x)=f(x-2)+f(x-3);

After having identified the recursive algorithm , we must identify the base cases:
This is really simple :
A score of 2 can only be achieved in one way by hitting a cannon and a score of 3 can only be achieved in one way by hitting an In-Off.
A score of 1 and 0 cannot be achieved.

The problem with using Recursion to solve this problem is that there will be many OverLapping Subproblems and it will be tremendously inefficient for large VALUES of X.
The Time Complexity of this approach would be O(2^X) which is not feasible at all.

OPTIMIZATION

We would use memoization (without recursion)(Iterative Bottom Up DP) to drastically reduce the Time Complexity to O(N).
Memoization requires Creating An Array of Size 10^6+1 .
Each Position Y in the Array would denote the answer for X=Y.
We would precompute the answers for each value Y where 1<=Y<=1000000 and then answer each query in O(1) Time.

We know that Array[0]=Array[1]=0 and Array[2]=Array[3]=1 .

Following values from 4 to 10^6 would use the relation :

Array[i]=(Array[i-2]+Arrays[i-3])%(10^9+9);

After precomputing the answers for each X we can simply print the answers in O(1) Time.

AUTHOR'S SOLUTION:

Author's solution .

CHEFYODA unofficial Editorial

$
0
0

CHEFYODA
Contest link
Let's consider Game1 in which only horizontal and vertical movements are allowed, One can easily see that yoda wins only when both N and M are odd.

In the other game, chef wins only when both N and M are even.

This reduces the problem to following

  • If chef is winning in both the games, output 1
  • If chef is losing in both the games, and P $\neq$ 0 , output 0. Else if P = 0, then output 1.
  • If chef is losing in 1 game and winning in other, then we need to calculate probbability of winning atleast P games out of K.

    This is given by binomial distribution as $\frac1 2^K $ $\sum_{i=P}^{K}$ $K\choose i$

    Now the task is to calculate $K\choose i$ for i = P to K. You can calculate this by using BigDecimal in Java or using Decimal in python. This would work for small test case and would give you 40 points. For large testcase, this would result in TLE, even if you set precision to 6 decimal places.

    Now, sum of last K - P terms is equal to sum of first K - P terms

    $\sum_{i=P}^{K}$ $K\choose i$ = $\sum_{i=0}^{K - P}$ $K\choose i$

    and as per following

    $\sum_{i=0}^{K - P}$ $ \le 2^{K - 1} \exp\frac{(K - 2(K - P) - 2)^2}{4(1+(K - P) -K)}$

    since Probability is $\frac1 2^K $ $\sum_{i=0}^{K - P}$ $K\choose i$, we have

    Probability $\le 2 ^{-1} \exp\frac{(K - 2(K - P) - 2)^2}{4(1+(K - P) -K)}$

    Now, for small values of P, probability would be close to 1 and we could answer 1 instead of finding out probability. Similarly, for large values of P, probability would be close to 0 and we could answer 0 instead of finding the probability.

    The first difference in output would occur when Probability = $10^{-6}$

    We can find the value of P by following

    $10 ^ {-6} = 2 ^{-1} \exp\frac{(K - 2(K - P) - 2)^2}{4(1+(K - P) -K)}$

    Substituting K = $10 ^ 5$ gives P = 49162 and 50821 Substituting K = $10 ^ 6$ gives P = 497370 and 502614

    Observe that these values are pretty close to $ \frac K 2$. We know that sum of all terms is $2^K$ and that the series is symetric. Therefore, sum of $ \frac K 2$ terms is $2^{K - 1}$. Now, we need to add or subtract atmost 3000 Terms from $2^{K - 1}$ to get probability.

    This can be done within the given timelimit and here is thecode

    You can also do it using Python Libraries code

ENIGMA01 - Editorial

$
0
0

PROBLEM LINK:

Guess the Number

Author and Editorialist :Kamini Pandey

DIFFICULTY:

Ad-hoc , Easy

PREREQUISITES:

Sieve of Eratosthenes

PROBLEM:

To guess what is minimum number of questions that are needed to be asked to correctly guess any number in the given range.

EXPLANATION:

The idea is to get the number of primes factor for all the numbers up to K. Firstly lets compute number of primes <= K (This part can be pre computed using Sieve of Eratosthenes ). Then for every prime ‘p’ we need to find highest ‘v’ such that pv<=K.

we add ‘v’ to the answer for each prime.

SOLUTION:

Link to Solution

ALG1705-Editorial

$
0
0

PROBLEM LINK:

Practice

Contest

Author:Vivek Kumar

DIFFICULTY:

HARD

EXPLANATION:

This problem is pure implementation problem.

To solve this problem, Please go through this wonderful editorial of this problem.

Now, suppose you know how to find the number of different substrings of a given string. So, to get Kth character in the concatenation of all substrings, You need to count the number of characters while calculating the length of LCP o ith and (i+1)th suffix in sorted order. Suppose length of the LCP is some L, and it was L' between (i-1)th suffix and ith suffix. then ith suffix will contribute to strings having length L'+1, L'+2...L. and we will keep adding all the length in this manner unless we get length upto k.

The main issue in this problem is not the algorithm, but implementation :)

AUTHOR SOLUTION:

Author's solution can be found here.

Viewing all 39796 articles
Browse latest View live


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