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

KOL1506 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Balajiganapathi
Tester:Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

Binomial theorem, dynamic programming

PROBLEM:

There are $N$ houses in a row. The position of the $i$th house is $A_i$. Each house sends a gift to every other house, and the cost of sending a gift from a house at position $x$ to a house at position $y$ is $|x-y|^k$. What is the total amount of money paid by all houses, modulo $10^9 + 7$?

QUICK EXPLANATION:

For $0 \le i \le N$ and $0 \le a \le k$, let $C_{i,a} := \sum_{j=1}^{i-1} (-A_j)^{k-a}$. These values can be computed in $O(Nk)$ using the recurrence: $$C_{i+1,a} = C_{i,a} + (-A_i)^{k-a}$$ The answer is now: $$2\sum_{i=1}^N \sum_{a=0}^k {k \choose a} C_{i,a} A_i^a$$ By precomputing binomial coefficients and powers of $A_i$, this answer can be computed in $O(Nk)$ time.

EXPLANATION:

Based on the problem itself, the answer is the following sum: $$\sum_{\substack{1 \le i, j \le N\\\ j \not= i}} |A_i - A_j|^k$$ We can reduce this sum in half by noticing that the cost of sending a gift from house $i$ to house $j$ is the same as sending a gift from house $j$ to house $i$.
$$2\sum_{1 \le j < i \le N} |A_i - A_j|^k$$ To remove the nasty absolute value in the formula, we can just sort the $A_i$s, so that if $j < i$, then $A_j \le A_i$. So assuming the $A_i$s are sorted, the sum is now: $$2\sum_{1 \le j < i \le N} (A_i - A_j)^k$$ or $$2\sum_{i=1}^N \sum_{j=1}^{i-1} (A_i - A_j)^k$$ For a fixed $i$, $1 \le i \le N$, we can interpret the inner sum as the total cost of sending a gift from house $i$ to all the other houses $j < i$. If we want to compute the answer quickly, we must be able to compute the inner sum quickly for each $i$.

We can manipulate the inner sum with the binomial theorem: $$\begin{align*} \sum_{j=1}^{i-1} (A_i - A_j)^k&= \sum_{j=1}^{i-1} \sum_{a=0}^k {k \choose a} A_i^a (-A_j)^{k-a} \\\&= \sum_{a=0}^k {k \choose a} \left(\sum_{j=1}^{i-1} (-A_j)^{k-a}\right) A_i^a\\\ \end{align*}$$ Let's define $C_{i,a} = \sum_{j=1}^{i-1} (-A_j)^{k-a}$ so that the sum above is simply equal to $$\sum_{a=0}^k {k \choose a} C_{i,a} A_i^a$$ Computing this sum for all $i$ naïvely will take $O(N^2k)$ time, because computing $C_{i,a}$ takes linear time for each $i$. We must be able to compute the $C_{i,a}$s quicker than this.

We can take advantage of the fact that $C_{i,a}$ and $C_{i+1,a}$ are related; The value $C_{i+1,a} - C_{i,a}$ is just $(-A_i)^{k-a}$. Thus, we have the following simple recurrence:
$$C_{i+1,a} = C_{i,a} + (-A_i)^{k-a}$$ Thus, if we know $C_{i,a}$ for all $a$, then we can use this recurrence to compute $C_{i+1,a}$ for all $a$ quickly, and if we can compute the $C_{i,a}$ values quickly, then we can find the answer to the problem quickly!

The pseudocode is as follows:

mod = 10^9 + 7
C = [0,0,0,...0] # length k+1
P = [0,0,0,...0] # length k+1

for i = 1...N:
    // compute powers of A[i]
    power = 1
    for a = 0...k:
        P[a] = power
        power *= A[i]

    // adjust answer
    for a = 0...k:
        answer += binom(k,a) * C[a] * P[a]

    // compute powers of -A[i]
    power = 1
    for a = 0...k:
        P[a] = power
        power *= -A[i]

    // adjust C's
    for a = 0...k:
        C[a] += P[k-a]

The running time is clearly $O(Nk)$, assuming we have already precomputed the binomial coefficients. Don't forget to reduce intermediate values modulo $10^9 + 7$!

Time Complexity:

$O(N \log N + Nk)$

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester


KOL1509 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Devendra Agarwal
Tester:Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

Convex hull

PROBLEM:

Given $A_1, \ldots, A_N$, a tree is planted at point $(A_i,A_j)$ for every pair $i < j$. What is twice the area enclosed by the minimum-perimeter fence surrounding the trees?

QUICK EXPLANATION:

For each $1 \le j \le N$, let $m(j) := \min _ {i< j} A _ i$ and $M(j) := \max _ {i< j} A _ i$. These values can be computed in linear time by maintaining the running minimum and maximum.

The answer is twice the area of the convex hull of the following set of (at most) $2N$ points: $$\{(m(j), A_j) : 1 \le j \le N\} \cup \{(M(j), A_j) : 1 \le j \le N\}$$ Twice the area of a lattice point polygon is always an integer, and this value can be computed using the shoelace formula: $$\text{twice the area} = \left|\sum_{i=1}^{\text{no. of vertices}} x_{i-1}y_i - y_{i-1}x_i\right|$$

EXPLANATION:

Convex hull

It doesn't take too long to discover that this "minimum perimeter fence" is just the convex hull of the given points. (If you're not convinced of this, see this link for an explanation, which also works in our case.) So we just want to compute the area of the convex hull of some $N(N-1)/2$ points. The problem is that this is a lot of points. Even just looping through all these points will exceed the time limit.

However, we can actually ignore most of them. For every three collinear points $A$, $B$ and $C$ in that order, $B$ can essentially be ignored. This is because a convex set by definition is a set containing all line segments between each pair of its points. Since the convex hull is convex, this means it contains the segment $AC$, which contains $B$ automatically. Thus, we can ignore $B$ altogether.

This means that we only need to keep at most two points in each horizontal line, the leftmost and rightmost. So for a fixed $j > 1$, we don't have to include all points $(A_i,A_j)$ for all $1 \le i < j$. We only need to include $\left(\min_{i< j} A_i,A_j\right)$ and $\left(\max_{i< j} A_i,A_j\right)$. This leaves us with at most $2N$ points, so any standard fast convex hull algorithm can now compute the convex hull of all points!

Area of a polygon

Finally, we need to compute twice the area of this polygon. Since the vertices are on lattice points, by Pick's theorem, twice the area is guaranteed to be an integer. But how do we compute it? We can use the area formula: For a polygon with $M$ vertices $(x_0,y_0),(x_1,y_1),\ldots (x_M,y_M)$ with $(x_0,y_0) = (x_M,y_M)$, the area is the following: $$\frac{1}{2} \left| \sum_{i=1}^M \left(x_{i-1}y_i - y_{i-1}x_i\right)\right|$$ (This is called the shoelace formula)

To get twice the area, simply ignore the $\frac{1}{2}$. This formula can be computed trivially in $O(M)$ time!

To get a sense of why this formula works, first ignore the absolute value signs. The resulting value, $$\sum_{i=1}^M \frac{1}{2} \left(x_{i-1}y_i - y_{i-1}x_i\right)$$ is known as the signed area of the polygon. The absolute value is the actual area, while the sign determines which direction we traversed the polygon: a counterclockwise traversal gives a positive sign, and a clockwise traversal gives a negative sign.

The value $\left(x_{i-1}y_i - y_{i-1}x_i\right)$ is the "cross product" of the vectors $\langle x_{i-1}, y_{i-1}\rangle$ and $\langle x_i,y_i\rangle$, which we can interpret as the signed area of the parallelogram with vertices $(0,0)$, $(x_{i-1},y_{i-1})$, $(x_{i-1}+x_i,y_{i-1}+y_i)$ and $(x_i,y_i)$. Thus, half of that value, $\frac{1}{2} \left(x_{i-1}y_i - y_{i-1}x_i\right)$, is the signed area of the triangle with vertices $(x_{i-1},y_{i-1})$, $(x_i,y_i)$, and the origin.

Under this interpretation, we can now interpret the signed area formula as the sum of signed areas of triangles along a counterclockwise traversal of the polygon. As we wrap around the polygon, these triangles with positive and negative area will overlap, but the parts outside the polygon will cancel out and sum to 0, leaving only the area inside the reference triangle. This works even if the origin is inside or outside the polygon. I recommend trying it out on paper!

Time Complexity:

$O(N \log N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

KOL1503 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Devendra Agarwal
Tester:Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

Lowest common ancestors, balanced parentheses

PROBLEM:

Given a tree with $N$ nodes, each node containing a parenthesis—) or (—, answer $Q$ queries of the following kind:

  • Given two nodes $u$ and $v$, consider the string obtained by taking all parenthesis characters from every node in the path from $u$ to $v$. Output Yes if this string is a balanced string of parentheses, otherwise print No.

QUICK EXPLANATION:

Root the tree. A path from $a$ to $b$ consists of two parts: A path from nodes $a$ to $b$ consists of two parts: the path from $a$ to $\text{LCA}(a,b)$ and from $\text{LCA}(a,b)$ to $b$. Take care that the node $\text{LCA}(a,b)$ is counted only once. By convention, let's say this node belongs at the first part of the path.

The string in the path from $a$ to $b$ is a valid parenthesization iff the following hold:

  • The path from $a$ to $\text{LCA}(a,b)$ is a prefix of a valid parenthesization.
  • The path from $\text{LCA}(a,b)$ to $b$ is a suffix of a valid parenthesization.
  • The number of unmatched open parentheses from $a$ to $\text{LCA}(a,b)$ is equal to the number of unmatched closed parentheses from $\text{LCA}(a,b)$ to $b$.

To check these conditions, we must be able to perform the following operations:

  • Given some path from some node to one of its ancestors, it is a prefix of a valid parenthesization?
  • Given some path from some node to one of its ancestors, it is a suffix of a valid parenthesization?
  • Given some node $x$ and one of its ancestors $y$, where the path from $x$ and $y$ is a prefix of a valid parenthesization, how many unmatched open parentheses are there?
  • Given some node $x$ and one of its ancestors $y$, where the path from $y$ and $x$ is a suffix of a valid parenthesization, how many unmatched closed parentheses are there?

The latter two can be done by precomputing $f(x)$ for each node $x$, where $f(x)$ is the number of open parentheses minus the number of closed parentheses from $x$ to the root. It can be computed using the recurrence: $$f(x) = \begin{cases} f(\text{parent}(x)) + 1 & \text{If the parenthesis at node $x$ is open} \\\ f(\text{parent}(x)) - 1 & \text{If the parenthesis at node $x$ is closed} \end{cases}$$

The former two can be done by precomputing $\text{pre}(x)$ and $\text{suf}(x)$ for each node $x$, which are defined as the lengths of the longest path from $x$ to the root that is a valid parenthesization prefix and suffix, respectively.

EXPLANATION:

As with many problems involving an undirected tree, the natural first step is to root it. This usually helps. So let's say the tree is rooted at node $1$.

A path from nodes $a$ to $b$ consists of two parts: the path from $a$ to $\text{LCA}(a,b)$ and from $\text{LCA}(a,b)$ to $b$ (where $\text{LCA}(a,b)$ is the lowest common ancestor of $a$ and $b$). But since the parentheses are on the nodes, not edges, so we need to ensure we count $\text{LCA}(a,b)$ only once. By convention, let's say this node belongs at the first part of the path, i.e. from the path from $a$ to $\text{LCA}(a,b)$, and when we say the "path from $\text{LCA}(a,b)$ to $b$", the node $\text{LCA}(a,b)$ isn't actually included.

Obviously, the string of parentheses in the path from $a$ to $\text{LCA}(a,b)$ must be a valid prefix of some valid parenthesization. Similarly the string from $\text{LCA}(a,b)$ to $b$ must be valid suffix. These are necessary conditions. However, they're not sufficient. For example, (((( is a valid prefix and )) is a valid suffix but combining them, (((()), doesn't yield a valid parenthesization. Obviously, we're missing a condition: the number of unmatched parentheses in both strings must be equal. It's easy to see that these are sufficient conditions, i.e. the path from $a$ to $b$ contains a valid parenthesization iff the following conditions hold:

  • The path from $a$ to $\text{LCA}(a,b)$ is a prefix of a valid parenthesization.
  • The path from $\text{LCA}(a,b)$ to $b$ is a suffix of a valid parenthesization.
  • The number of unmatched open parentheses from $a$ to $\text{LCA}(a,b)$ is equal to the number of unmatched closed parentheses from $\text{LCA}(a,b)$ to $b$.

(Remember the convention that $\text{LCA}(a,b)$ only belongs to the path from $a$ to $\text{LCA}(a,b)$.)

So we want perform the following operations quickly:

  • Given some path from some node to one of its ancestors, it is a prefix of a valid parenthesization?
  • Given some path from some node to one of its ancestors, it is a suffix of a valid parenthesization?
  • Given some node $x$ and one of its ancestors $y$, where the path from $x$ and $y$ is a prefix of a valid parenthesization, how many unmatched open parentheses are there?
  • Given some node $x$ and one of its ancestors $y$, where the path from $y$ and $x$ is a suffix of a valid parenthesization, how many unmatched closed parentheses are there?

But the latter two can be computed with the following: Let $f(x)$ be the number of open parentheses minus the number of closed parentheses from $x$ to the root (node $1$). Then:

  • The number of unmatched parentheses from $x$ to $y$ is just $|f(x) - f(\text{parent}(y))|$. (If $y = 1$, then we say $f(\text{parent}(y)) = 0$ by convention.)
  • Also, these unmatched parentheses are open parentheses if $f(x) > f(\text{parent}(y))$, otherwise they're closed parentheses.

Thus, having the $f(x)$ values allows us to perform the operations above. Additionally, the $f(x)$s can be precomputed in linear time with a single traversal of the tree, using the following:

  • If the parenthesis at node $x$ is (, then $f(x) = f(\text{parent}(x)) + 1$. Otherwise, $f(x) = f(\text{parent}(x)) - 1$.

The precomputation runs in linear time. What remains is to efficiently answer the following queries:

  • Given some path from some node to one of its ancestors, it is a prefix of a valid parenthesization?
  • Given some path from some node to one of its ancestors, it is a suffix of a valid parenthesization?

These two operations are very similar, so we will just describe one of them, say the first one. To perform this query, we use the following characterization of a valid parenthesization prefix:

A string is a prefix of a valid parenthesization if every prefix of it contains at least as many open parentheses as there are closed parentheses.

In terms of our tree, this is equivalent to saying that:

If $y$ is an ancestor of $x$, then the path from $x$ to $y$ forms a prefix of a valid parenthesization if and only if $f(x) \ge f(\text{parent}(z))$ for every node $z$ in the path.

That this is true can be seen from the meaning of the inequality $f(x) \ge f(\text{parent}(z))$. Note that $f(x) - f(\text{parent}(z))$ is the number of unmatched open parentheses from $x$ to $z$, so if this is $\ge 0$, for every node $z$ in the path, then the condition for being a valid parenthesization prefix is satisfied.

For every node $x$, we define $\text{pre}(x)$ as the length of the longest path from $x$ to the root that is a valid parenthesization prefix (in terms of the number of nodes). Using the property above, the path from $x$ to its ancestor $y$ is a valid parenthesization prefix if and only if $\text{depth}(x) - \text{depth}(y) < \text{pre}(x)$. So we can answer the queries if we have $\text{depth}(x)$ and $\text{pre}(x)$ for all nodes $x$. Precomputing the depths of nodes can be done with a single traversal, so what remains is to compute $\text{pre}(x)$ for all nodes $x$.

We will also compute the $\text{pre}(x)$s with a single traversal. Let $z$ be the $\text{pre}(x)$th ancestor of $x$. If $z$ is not the root, then let $y = \text{parent}(z)$. Then $y$ is the first node such that $f(x) < f(y)$. Since the $f$s only differ by one between adjacent nodes, this means that $f(z)$ must be equal to $f(x)$, and $f(y)$ must be equal to $f(x) + 1$. So $\text{pre}(x)$ is just the distance of $x$ to its nearest ancestor $y$ whose $f(y)$ is $f(x) + 1$. (And if no such $y$s exist, then $\text{pre}(x)$ is just $\text{depth}(x)+1$.) Obviously, if the parenthesis at $x$ is ), then $\text{pre}(x)$ is automatically $0$.

Thus, as we traverse the tree, we must be able to answer the following query quickly:

  • Given $v$, find the nearest ancestor $y$ of the current node such that $f(y) = v$.

This can be done by maintaining a map of lists, which lists for each $v$ the nodes $y$ along the path to the root whose $f(y) = v$. The following pseudocode illustrates it better:

// arrays are initialized to zero
f = array[0...N]
parent = array[1...N]
depth = array[0...N]
pre = array[1...N]
m = {}

def PUSH(x,d):
    if d is not a key of m:
        m[d] = new empty list()

    add x at the end of m[d]

def GET(d):
    if d is not a key of m:
        return 0
    else:
        return the last element of m[d]

def POP(x,d):
    remove x from the end of m[d]
    if m[d] is empty:
        delete the key d from m

def traverse(x):

    // compute f[x]
    if parenthesis(x) == '(':
        f[x] = f[parent[x]] + 1
    else:
        f[x] = f[parent[x]] - 1

    // compute depth[x]
    depth[x] = depth[parent[x]] + 1

    // compute pre[x]
    if parenthesis(x) == ')':
        pre[x] = 0
    else:
        y = GET(f[x] + 1)
        pre[x] = depth[x] - depth[y]

    // add x
    PUSH(x, f[x])

    for j in adj[x]:
        if j != parent[x]:
            parent[j] = x
            traverse(j)

    // remove x
    POP(x, f[x])

// initial call is traverse(1)

A similar algorithm can be done to compute $\text{suf}(x)$ for all nodes $x$, which is defined as the length of the longest path from $x$ to the root that is a valid parenthesization suffix. Using $\text{pre}(x)$ and $\text{suf}(x)$, one can now answer the queries above in $O(1)$ time!

By precomputing $f(x)$, $\text{pre}(x)$ and $\text{suf}(x)$ for all nodes $x$, each query can be answered in $O(\log N)$ time (because we're taking the LCA of the two nodes.)

Note: If you find the number of unmatched parentheses in this document a bit disturbing, here's something that can make it worse.

Time Complexity:

$O((N + Q)\log N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

KOL1501 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Devendra Agarwal
Tester:Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

Dynamic programming, long multiplication

PROBLEM:

In an alien world using the base 10 number system, the long multiplication algorithm is the same as Earth's, except that digit-by-digit multiplication may be different. The results of all 100 digit multiplications are given, and it's also guaranteed that any digit multiplied by 0 is 0, and multiplication of digits is commutative.

Given $A < 10^{100000}$, compute the "alien product" of $i$ and $j$ for all pairs $(i,j)$ of integers between $1$ and $A$, inclusive. Output this value modulo $M$ (given as input).

QUICK EXPLANATION:

Let $\text{count}(i,x)$ be the number of numbers between $0$ and $A$ whose $i$th least significant digit is $x$. Let $$F(x) = \sum_{i=0}^{l(A)-1} 10^i \text{count}(x,i)$$ Then the answer is: $$\sum_{x=0}^9 \sum_{y=0}^9 (x\circ y) F(x) F(y)$$ Where $x\circ y$ denotes alien digit multiplication. $\text{count}(x,i)$ can be computed using the following: (where $A_i$ is the $i$th least significant digit of $A$) $$\text{count}(x,i) = \begin{cases} \lfloor A / 10^{i+1} \rfloor\cdot 10^i & \text{if $x > A_i$} \\\ \lfloor A / 10^{i+1} \rfloor\cdot 10^i + 10^i & \text{if $x < A_i$} \\\ \lfloor A / 10^{i+1} \rfloor\cdot 10^i + (A \bmod 10^i) + 1 & \text{if $x = A_i$} \end{cases}$$ Define $$A_{\text{div}}(i) = \lfloor A / 10^i \rfloor \bmod M$$ $$A_{\text{mod}}(i) = (A \bmod 10^i) \bmod M$$

The $A_{\text{div}}(i)$ and $A_{\text{mod}}(i)$ values can be precomputed modulo $M$ using the following recurrences: $$A_{\text{div}}(i) = (A_{\text{div}}(i+1)\cdot 10 + A_i) \bmod M$$ $$A_{\text{mod}}(i) = (A_{\text{mod}}(i-1) + 10^{i-1}A_{i-1}) \bmod M$$ with base cases $A_{\text{div}}(\text{length}(A)) = 0$ and $A_{\text{mod}}(0) = 0$.

EXPLANATION:

In order to distinguish normal multiplication from alien multiplication, we need to use a different notation. Let's use $x \circ y$ as the notation for "alien multiplication", while the usual multiplication notations ($\times$, $\cdot$, and juxtaposition) will denote normal Earthling multiplication. Thus, the answer is: $$\sum_{a=1}^A \sum_{b=1}^A (a \circ b)$$ Earthling multiplication has a lot of nice properties that alien multiplication doesn't have, such as:

  • $x \cdot (y \cdot z) = (x \cdot y) \cdot z$ (Associativity)
  • $x \cdot (y + z) = (x \cdot z) + (y \cdot z)$ (Distributivity)
  • $x \cdot 1 = x$ (Identity)

Thus, it seems hard to compute the answer because we can't seem to do anything sensible. But there are still a few nice properties left:

  • $x\circ y = y\circ x$ (Commutativity)
  • $x\circ 0 = 0\circ x = 0$

These are properties that hold for all numbers $x$ and $y$, not just digits.

In addition, the alien "long multiplication" method is very similar to Earthling "long multiplication". In fact, they are similar enough that we can formulate the following description of the alien product $a\circ b$ of two numbers: (where we denote by $l(a)$ the number of digits of a number $a$)

  • Let $a = (a_{l(a)-1}, a_{l(a)-2}, \ldots, a_1, a_0)$ be the digits of $a$ in base 10.
  • Let $b = (b_{l(b)-1}, b_{l(b)-2}, \ldots, b_1, b_0)$ be the digits of $b$ in base 10.

Then:
$$a\circ b = \sum_{i=0}^{l(a)-1} \sum_{j=0}^{l(b)-1} (a_i \circ b_j)\cdot 10^{i+j}$$

We can rearrange this by looping through all values of $a_i$ and $b_j$ (from $0$ to $9$):

$$\begin{align*} \sum_{i=0}^{l(a)-1} \sum_{j=0}^{l(b)-1} (a_i \circ b_j)10^{i+j}&= \sum_{x=0}^9 \sum_{y=0}^9 \sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} \sum_{\substack{j=0 \\\ b_j=y}}^{l(b)-1} (x\circ y)\cdot 10^{i+j} \\\&= \sum_{x=0}^9 \sum_{y=0}^9 (x\circ y) \sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} \sum_{\substack{j=0 \\\ b_j=y}}^{l(b)-1} 10^{i+j} \\\&= \sum_{x=0}^9 \sum_{y=0}^9 (x\circ y) \sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} \sum_{\substack{j=0 \\\ b_j=y}}^{l(b)-1} 10^i 10^j \\\&= \sum_{x=0}^9 \sum_{y=0}^9 (x\circ y) \left(\sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} 10^i \right)\cdot \left(\sum_{\substack{j=0 \\\ b_j=y}}^{l(b)-1} 10^j\right) \end{align*}$$

This is the result of a single alien multiplication. But we want to sum all such results among all pairs. Thankfully, the alient product $(x\circ y)$ has been moved away from the inner sum, so the problem looks much easier now.

Let's define $S(x,y)$ as the inner sum, summed across all possible values $a$ and $b$:
$$S(x,y) = \sum_{a=0}^A \sum_{b=0}^A \left(\sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} 10^i \right)\cdot \left(\sum_{\substack{j=0 \\\ b_j=y}}^{l(b)-1} 10^j\right)$$
We included the cases $a = 0$ and $b = 0$. This is okay because the alien product of 0 with anything is 0 anyway. But this will help us later on.

Thus, the final answer is now: $$\sum_{x=0}^9 \sum_{y=0}^9 (x\circ y) S(x,y)$$ Our goal now is to compute $S(x,y)$ for all digits $x$ and $y$. Let's fix $x$ and $y$. Notice that: $$\begin{align*} S(x,y)&= \sum_{a=0}^A \sum_{b=0}^A \left(\sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} 10^i \right)\cdot \left(\sum_{\substack{j=0 \\\ b_j=y}}^{l(b)-1} 10^j\right) \\\&= \left(\sum_{a=0}^A \sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} 10^i \right)\cdot \left(\sum_{b=0}^A \sum_{\substack{j=0 \\\ b_j=y}}^{l(b)-1} 10^j\right) \end{align*}$$
If we define $F(x)$ as the following: $$F(x) = \sum_{a=0}^A \sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} 10^i$$ Then we can substitute this above to get: $$S(x,y) = F(x)F(y)$$ Thus, all we have to do now is compute $F(x)$ for all digits $x$. Now it really seems we're getting somewhere!

Let's swap the summation for $F(x)$:
$$\begin{align*} F(x)&= \sum_{a=0}^A \sum_{\substack{i=0 \\\ a_i=x}}^{l(a)-1} 10^i \\\&= \sum_{i=0}^{l(A)-1} \sum_{\substack{a=0 \\\ a_i=x}}^A 10^i \\\&= \sum_{i=0}^{l(A)-1} 10^i \sum_{\substack{a=0 \\\ a_i=x}}^A 1 \end{align*}$$

The inner sum is just the number of numbers between $0$ and $A$ whose $i$th least significant digit is $x$. Let's define $\text{count}(x,i)$ to be this number, so that: $$F(x) = \sum_{i=0}^{l(A)-1} 10^i \text{count}(x,i)$$ and we now want to compute $\text{count}(x,i)$ for each digit $x$ and each position $i$. How many ways can you construct a number $a$ between $0$ and $A$ such that the $i$th digit from the last is $x$?

Let's count the number of ways to choose the other digits of $a$ (since we know that $a_i$ must be $x$). One necessary condition is that the number represented by the digits $(a_{l(A)-1}, a_{l(A)-2}, \ldots, a_{i+1})$ must not be greater than $(A_{l(A)-1}, A_{l(A)-2}, \ldots, A_{i+1})$. There are two remaining cases:

  • In the first case, $(a_{l(A)-1}, a_{l(A)-2}, \ldots, a_{i+1})$ is less than $(A_{l(A)-1}, A_{l(A)-2}, \ldots, A_{i+1})$. In this case, it doesn't matter what the remaining digits are, because $a$ is already less than $A$. Thus, there are $10^i$ ways to choose the digits less significant than $a_i$, and there are $\lfloor A / 10^{i+1} \rfloor$ ways to choose the digits more significant than $a_i$. Thus, there are $\lfloor A / 10^{i+1} \rfloor\cdot 10^i$ numbers in this case.
  • In the second case, $(a_{l(A)-1}, a_{l(A)-2}, \ldots, a_{i+1})$ is equal $(A_{l(A)-1}, A_{l(A)-2}, \ldots, A_{i+1})$. Here we can essentially ignore the digits more significant than $a_i$. Now, if $x > A_i$, then $a$ already becomes $> A$ regardless of the choice of other digits, so it must be the case that $x \le A_i$. There are two sub-cases:

    • If $x < A_i$, then $a$ is already $< A$, so we can choose the lower-order digits anyway we want. There are $10^i$ choices for those digits.
    • If $x = A_i$, then the digits $(a_{i-1}, a_{i-2}, \ldots a_0)$ must be at most $(A_{i-1}, A_{i-2}, \ldots A_0)$. There are at most $(A \bmod 10^i) + 1$ ways to choose these digits.

Thus, by combining all cases together, we now have a formula for $\text{count}(x,i)$:
$$\text{count}(x,i) = \begin{cases} \lfloor A / 10^{i+1} \rfloor\cdot 10^i & \text{if $x > A_i$} \\\ \lfloor A / 10^{i+1} \rfloor\cdot 10^i + 10^i & \text{if $x < A_i$} \\\ \lfloor A / 10^{i+1} \rfloor\cdot 10^i + (A \bmod 10^i) + 1 & \text{if $x = A_i$} \end{cases}$$ Finally, these numbers are very large so we need to compute them modulo $M$. For $0 \le i < l(A)$, let's define: $$A_{\text{div}}(i) = \lfloor A / 10^i \rfloor \bmod M$$ $$A_{\text{mod}}(i) = (A \bmod 10^i) \bmod M$$ Substituting these to the formula for $\text{count}(x,i)$, we get: $$\text{count}(x,i) = \begin{cases} A_{\text{div}}(i+1) \cdot 10^i & \text{if $x > A_i$} \\\ A_{\text{div}}(i+1) \cdot 10^i + 10^i & \text{if $x < A_i$} \\\ A_{\text{div}}(i+1) \cdot 10^i + A_{\text{mod}}(i) + 1 & \text{if $x = A_i$} \end{cases}$$

But the $A_{\text{div}}(i)$s and $A_{\text{mod}}(i)$s can be computed with dynamic programming using the following recurrences (straightforward to prove):
$$A_{\text{div}}(i) = (A_{\text{div}}(i+1)\cdot 10 + A_i) \bmod M$$ $$A_{\text{mod}}(i) = (A_{\text{mod}}(i-1) + 10^{i-1}A_{i-1}) \bmod M$$ with base cases $A_{\text{div}}(l(A)) = 0$ and $A_{\text{mod}}(0) = 0$.

This gives us a linear-time algorithm to compute the answer!

  • Compute the $A_{\text{div}}(i)$s and $A_{\text{mod}}(i)$s.
  • Compute the $\text{count}(x,i)$s, modulo $M$.
  • Compute the $F(x)$s, modulo $M$.
  • Compute the $S(x,y)$s, modulo $M$.
  • Finally, compute the final answer using the $S(x,y)$ values.

Time Complexity:

$O(\log A)$ (note that $A$ has approximately $\log_{10} A + 1$ digits)

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

KOL1502 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Devendra Agarwal
Tester:Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

Dynamic programming

PROBLEM:

There are $N$ ingredients, each having a taste score between $1$ to $10$. A dish is made out of the $2^N$ possible combinations of ingredients (including the empty set).

Planet A will pay for a dish the sum of the taste scores of ingredients in the dish, minus the sum of the taste scores of ingredients not in the dish.

Planet B will pay for a dish the sum of the taste scores of ingredients not in the dish, minus the sum of the taste scores of ingredients in the dish.

Each dish can be given only to one planet. What is the maximum amount of money that can be made? Give your answer modulo $10^7$.

QUICK EXPLANATION:

For $-10N \le t \le 10N$ and $0 \le i \le N$, let $F(i,t)$ be the number (modulo $10^7$) of dishes $S$ such that $A(S) = t$, considering only the first $i$ ingredients. The answer can be calculated as:
$$\sum_{t=-10N}^{10N} |t| F(N,t)$$

$F(i,t)$ can be computed with dynamic programming using the following recurrence: $$F(i,t) = (F(i-1, t - t_i) + F(i-1, t + t_i)) \bmod 10^7$$ where we define $F(i,t) = 0$ when $|t| > 10N$. For the base case, we have $F(0,t) = 0$ for $t \not= 0$, but $F(0,t) = 1$ for $t = 0$. By filling the table $F(i,t)$ in increasing order of $i$, we will have access to the $F(N,t)$ values, and then the answer can be computed.

EXPLANATION:

Let's represent an ingredient as an integer from $1$ to $N$, and a dish as a subset of the set of ingredients, $[N] := \{1, 2, \ldots, N\}$. Also, let's write the taste score of ingredient $i$ as $t_i$.

For a given dish $S$ (which is a subset of $[N]$), let $A(S)$ and $B(S)$ be its value to planet A and planet B, respectively.

Note that the value of a dish can be negative. However, due to the way the planets calculate the value of a dish, it's easy to see that $A(S) = -B(S)$. Thus, if a dish has value to $2411$ to one planet, then it has value $-2411$ to another planet. So to make the most money, there's only one obvious choice of planet to give each dish to (unless its value is $0$), and the amount of money we can get from a particular dish is just $|A(S)|$ (or equivalently $|B(S)|$). So the answer is just the sum of $|A(S)|$ for all dishes $S$.

Dynamic programming

Obviously, calculating this sum naïvely will not pass, because there are up to $2^N$ dishes. We need to find a better way. We can do so by exploiting the fact that $1 \le t_i \le 10$, so the maximum $|A(S)|$ among all dishes is $10N \le 10000$.

For $-10N \le t \le 10N$ and $0 \le i \le N$, let $F(i,t)$ be the number (modulo $10^7$) of dishes $S$ such that $A(S) = t$, considering only the first $i$ ingredients. Such a function is useful to us because it gives us the number of dishes for each possible sum, so that the answer can be calculated as:
$$\sum_{t=-10N}^{10N} |t| F(N,t)$$ Now, it's time to find a recurrence for $F(i,t)$ (so that we can solve the problem with dynamic programming). Consider the $i$th ingredient. Its taste score is $t_i$. Also, let $S$ be some dish from the first $i-1$ ingredients. There are two options: either to include the $i$th ingredient or not. If we include it, the value of the dish becomes $A(S) + t_i$, otherwise, it becomes $A(S) - t_i$. In the former case, we want $A(S) + t_i$ to equal $t$, which means $A(S) = t - t_i$. In the latter case, we have $A(S) = t + t_i$. Thus, we now have the following recurrence:
$$F(i,t) = F(i-1, t - t_i) + F(i-1, t + t_i)$$ where we define $F(i,t) = 0$ when $|t| > 10N$. For the base case, we have $F(0,t) = 0$ for $t \not= 0$, but $F(0,t) = 1$ for $t = 0$ (representing the empty dish having the value $0$). This gives us a recurrence for computing $F(i,t)$. By constructing a table for $F(i,t)$ and computing its entries in increasing $i$ order, we can now have access to the $F(N,t)$ values and compute the answer. Don't forget to reduce your values modulo $10^7$!

The running time of this approach is $O(sN)$, where $s = t_1 + \ldots + t_N$. Alternatively, it is $O(t_{\max}N^2)$, where $t_{\max}$ is the maximum $t_i$.

Improvements

There are a couple of improvements that can be done over the above approach.

Let's start with a simple one. The above approach requires a table of size $N\times 10N$, or up to $10^7$ entries. We can reduce this to just $2\times 10N$ by keeping only two rows of the table at a time, because we only need the previous row to calculate the next row. This gives us a significant improvement in memory usage.

We can even reduce this by using only one row. But to do so, we must offset each row. Let's define a new function $G(i,t) = F(i,t - (t_1 + t_2 + \ldots + t_i))$. For a fixed $i$, row $i$ of $G$ is just row $i$ of $F$ offset $(t_1 + \ldots + t_i)$ units to the right. It's straightforward to compute a table entry for $G$ given an entry for $F$, and vice versa, but in switching to $G$, we ensure that the indices of $G$ are nonnegative, and we have the following equally-nice recurrence: $$G(i,t) = G(i-1,t) + G(i-1,t - 2t_i)$$ with base case $G(0,t) = [t = 0]$. (Iverson bracket notation).

Using this recurrence, we can compute each row of $G$ from the previous row in place (i.e. without requiring separate storage for the previous and current rows), by computing the $G(i,t)$s in decreasing order of $t$.

We can still halve the memory usage! Notice that the only entries of $G(i,t)$ that are nonzero are those where $t$ is even. So we can define a new function, $H(i,t)$, as $G(i,t/2)$, and we have the following recurrence:
$$H(i,t) = H(i-1,t) + H(i-1,t-t_i)$$ with base case $H(0,t) = [t = 0]$. Each row of $H$ is only half the size of the corresponding row in $G$!

Connections with polynomials

We can state the $F(i,t)$ values in terms of polynomials. Consider the "polynomial" $F_i(x) = \sum_{t=-\infty}^{\infty} F(i,t) x^t$. (We quote "polynomial" because it's not really a polynomial; the exponent of $x$ can be negative. Instead, this is called a Laurent polynomial.) Based on the recurrence for $F(i,t)$, we can express $F_i(x)$ in terms of $F_{i-1}(x)$ as follows: (In the following, the sum is assumed to range across all integers $t$) $$\begin{align*} F_i(x)&= \sum_t F(i,t) x^t \\\&= \sum_t [F(i-1,t-t_i) + F(i-1,t+t_i)] x^t \\\&= \sum_t F(i-1,t-t_i) x^t + \sum_t F(i-1,t+t_i) x^t \\\&= \sum_t F(i-1,t) x^{t+t_i} + \sum_t F(i-1,t) x^{t-t_i} \\\&= x^{t_i} \sum_t F(i-1,t) x^t + x^{-t_i} \sum_t F(i-1,t) x^t \\\&= \left(x^{t_i} + x^{-t_i}\right)\left(\sum_t F(i-1,t) x^t\right) \\\&= \left(x^{t_i} + x^{-t_i}\right)F_{i-1}(x) \end{align*}$$ (The fourth step is just replacement of indices)

And for the base case, we have $F_0(x) = 1$. In fact, by unrolling this recursion, we can get:

$$F_N(x) = \prod_{i=1}^N \left(x^{t_i} + x^{-t_i}\right)$$

Thus, $F(N,t)$ is just the coefficient of $x^t$ in $\prod_{i=1}^N \left(x^{t_i} + x^{-t_i}\right)$.

The transition we did to using $G(i,t)$ and $H(i,t)$ can also be realized in terms of polynomials. Define $G_i(x)$ and $H_i(x)$ similarly as $F_i(x)$. Then we have $G_i(x) = x^{t_1+\ldots+t_i}F_i(x)$ and $G_i(x) = H_i(x^2)$, and: $$\begin{align*} G_i(x) &= \left(x^{2t_i} + 1\right)G_{i-1}(x) \\\ H_i(x) &= \left(x^{t_i} + 1\right)H_{i-1}(x) \end{align*}$$ And $G_i(x)$ and $H_i(x)$ are actual polynomials, instead of just Laurent polynomials.

Finally, all these talk about polynomials isn't just for theoretical interest; they can be converted into an algorithm too. Note that we can extract the $H(N,t)$ values (and thus the answer) by computing the coefficients of $H_N(x)$, so all we have to do is compute the following polynomial product:
$$H_N(x) = \prod_{i=1}^N \left(x^{t_i} + 1\right)$$ But such a polynomial product can be computed quickly with FFT with binary splitting! In more detail:

  • Define $H_{a,b}(x) = \prod_{i=a+1}^b \left(x^{t_i} + 1\right)$. (In other words, $H_{a,b}(x) = H_b(x) / H_a(x)$.)
  • For $a < c < b$, we have $H_{a,b}(x) = H_{a,c}(x) H_{c,b}(x)$.
  • If $b - a = 1$, then $H_{a,b}(x)$ is just $x^{t_b} + 1$.
  • To compute $H_{a,b}(x)$ for $b - a \ge 2$, let $c = \left\lfloor \frac{a+b}{2} \right\rfloor$, and compute $H_{a,c}(x)$ and $H_{c,b}(x)$ recursively. Then compute $H_{a,b}(x)$ as the polynomial product of $H_{a,c}(x)$ and $H_{c,b}(x)$, which can be done quickly with FFT-based multiplication.

This gives us an $O(Nt_{\max} \log (Nt_{\max}) \log N)$-time algorithm!

Time Complexity:

$O(sN)$ where $s$ is the sum of all taste scores

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

KOL1504 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Devendra Aggarwal
Tester:Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

Sorting

PROBLEM:

Given two lowercase strings, each of length $N$, determine if you can transform the first string into the second by swapping letters that are positioned exactly $D$ apart.

QUICK EXPLANATION:

Let $s$ be the first string and $t$ be the second string. Let $s_i$ and $t_i$ be the $i$th letters of $s$ and $t$, respectively.

For each $i$, $1 \le i \le D$, check whether the following are the same multisets of letters: $$\{s_i, s_{i+D}, s_{i+2D}, \ldots\}$$ $$\{t_i, t_{i+D}, t_{i+2D}, \ldots\}$$ It can be done in $O(N/D)$ by simply counting the letters. If they are the same for all $i$, then the answer is Yes. Otherwise, it is No.

EXPLANATION:

Let $s$ be the first string and $t$ be the second string. Let $s_i$ and $t_i$ be the $i$th letters of $s$ and $t$, respectively.

If we can swap any pair of letters, obviously we can turn $s$ and $t$, as long as the multiset of letters of $s$ and $t$ are the same. But we can only swap letters that are of distance $D$ apart, and this can be rather restricting. For example, the letter at position $1$ can only have the following final positions: $$1, 1 + D, 1 + 2D, 1 + 3D, \ldots$$ More generally, an letter at position $i$ can only have the final positions $i, i + D, i + 2D, \ldots$. Not only that, but also $i - D, i - 2D, i - 3D, \ldots$. in other words, $i + kd$ for integer $k$.

Another way of stating this is: a letter at position $i$ can have the final position $j$ if and only if $i \equiv j \pmod{D}$ (using congruence notation). Thus, we know that any letters at positions $i$ and $j$ such that $i \not\equiv j \pmod{D}$ will never be able to interact with each other, so we may split $s$ and $t$ into $D$ subsequences, where we can only rearrange elements belonging to the same subsequence. For $1 \le i \le D$, let's define $s(i)$ as the subsequence of $s$ starting from position $i$ and taking every $D$th letter. Thus: $$\begin{align*} s(1) &= (s_1, s_{1+D}, s_{1+2D}, \ldots) \\\ s(2) &= (s_2, s_{2+D}, s_{2+2D}, \ldots) \\\ s(3) &= (s_3, s_{3+D}, s_{3+2D}, \ldots) \\\& \ldots \end{align*}$$ Define $t(i)$ similarly. Now, we can only swap consecutive letters belonging to the same subsequence, and for each $i$, only $s(i)$'s letters can be used to form $t(i)$. Thus, we have the following necessary condition for being able to transform $s$ to $t$:

If $s$ can be transformed to $t$, then for each $i$, $s(i)$ and $t(i)$ must have same multiset of letters.

But is this sufficient? In fact it is. Consider first the case $D = 1$. In this case, there's only one subsequence for each string, $s(1)$ and $t(1)$, and these are just equal to $s$ and $t$, respectively. The question becomes: can we make any $s$ be any other $t$, assuming they have the same multiset of letters, and we can only swap consecutive letters (because $D = 1$)? In fact, yes! The idea is to sort $s$, then "unsort" it to $t$ (i.e. take the reverse of the sequence of swaps that sort the letters of $t$). This works because there exists sorting algorithms that only swaps consecutive elements. (For example, insertion sort or bubble sort.)

For a general $D$, since we can swap consecutive letters in a subsequence $s(i)$, one can perform a similar algorithm to transform each $s(i)$ to $t(i)$ (assuming they have the same multiset of letters). We have just shown that the converse to the above is true:

If for each $i$, $s(i)$ and $t(i)$ must have same multiset of letters, then $s$ can be transformed to $t$.

The algorithm now is simple: just count how many times each character appears in $s(i)$, and check that these counts are the same as those for $t(i)$ (for each $i$).

A gotcha: Be careful that your implementation runs in $O(N)$, not $O(N+D)$! Otherwise, your solution will exceed the time limit. (Consider a file with $T = 100000$, each with $N = 1$ and $D = 100000$.)

Time Complexity:

$O(N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

KOL1505 - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:admin
Tester:Kevin Atienza
Editorialist:Kevin Atienza

PREREQUISITES:

String processing

PROBLEM:

Given two strings, the following operation can be done in any string: given two consecutive, same, letters, remove one of them. Can we make the two strings equal?

QUICK EXPLANATION:

Simply remove all consecutive duplicate letters in both strings (leaving just one for each consecutive sequence), and check if the resulting strings are equal.

EXPLANATION:

The solution should be apparent: Simply remove all consecutive duplicate letters in both strings (leaving just one for each consecutive sequence), and check if the resulting strings are equal. This is correct because if we can turn both strings into a string having consecutive duplicate letters, then we can continue removing the duplicates until we are left with none, thus both strings can be turned into the same string but having no consecutive duplicate letters.

Here's one way to perform it, in C:

void remove_duplicates(char *c) {
    int i = 1;
    for (int j = 1; c[j]; j++) {
        if (c[j] != c[j-1]) c[i++] = c[j];
    }
    c[i] = 0;
}

This performs the operation in-place, destroying the original string in the process.

There's a nice way to do it in C++:

string remove_duplicates(string s) {
    return string(s.begin(), unique(s.begin(), s.end()));
}

It uses the std::unique function, which does exactly what we want!

Finally, in Java:

static String removeDuplicates(String s) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        if (i == 0 || s.charAt(i-1) != s.charAt(i)) sb.append(s.charAt(i));
    }
    return sb.toString();
}

After implementing this function, simply call this on both input strings, and check if they are equal!

Gotcha: A possible mistake one can make when implementing string comparison is stopping the comparison prematurely. Consider the following C code: (It prints Yes if a and b are the same string, and No otherwise.)

bool good = true;
int a_len = strlen(a);
int b_len = strlen(b);
for (int i = 0; i < a_len && i < b_len; i++) {
    if (a[i] != b[i]) {
        good = false;
        break;
    }
}
puts(good ? "Yes" : "No");

Can you point out what's wrong with it?

The code above is wrong because it fails when a is a proper prefix of b, or vice versa. This is because good only becomes false when it finds two different characters in the same position from a and b, which isn't the case when one is a prefix of the other. Here are a couple of ways to fix this:

  • Check whether the lengths are equal first.
  • Replace the loop condition by i < a_len || i < b_len,
  • Better yet, just use builtin methods like strcmp.

Extra: There's a Unix utility that does this. The uniq command, when fed some text input, outputs it, but with adjacent identical lines collapsed to one. This is usually coupled with the sort command to output all distinct lines in the input.

Time Complexity:

$O(|s| + |t|)$

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

INOI 2015 Periodic strings Problem


Enormous Input Test ( INTEST)

$
0
0

here is a link of my solution...

http://www.codechef.com/viewsolution/3651260

when i am running this code on ideone.com it is giving count of divisible number by k actual count + 1 ....means if ans is count =4 then it is giving count =5....so i hav submitted my solution printing count-1.....can anyone help to tell me how it is coming...thanks

GERALD04 - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Gerald Agapov
Tester:Tasnim Imran Sunny
Editorialist:Jingbo Shang

DIFFICULTY:

Cakewalk

PREREQUISITES:

Programming

PROBLEM:

GF --- (t2 - t1) --- Chef --- dist --- Home

Given t1, t2, dist, determine the time costs before GF see the gift of two plans:

  1. Chef waits for GF, and then goes home together.
  2. Chef returns home first, and goes back to GF.

EXPLANATION:

For the first plan, the answer should be (t2 - t1) + dist.

For the second one, it will be a little complicated. We need to discuss in 2 cases:

  1. If dist + dist <= t2 - t1, then Chef can return the bus station before GF arrived. Therefore, the answer should be t2 - t1.
  2. If t2 - t1 < dist + dist, then they will meet at the trip of going back. Therefore, the answer should be the middle point of the trip (imagine that the three parts as a whole): (t2 - t1 + dist * 2) / 2.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

how to divide strings

$
0
0

Kevin has a string S consisting of N lowercase English letters.

Kevin wants to split it into 4 pairwise different non-empty parts. For example, string "happynewyear" can be splitted into "happy", "new", "ye" and "ar". He can't delete any characters or change the order of the characters.

Help Kevin and find if there exist at least one possible spliting.

Input format:

The first line of input will contain an integer T, denoting the number of test cases. Each of the next T lines contains a string S.

Output format:

For every test case output "YES" if it is possible to split the string and "NO" otherwise.

Constraints:

1 ≤ T ≤ 100 1 ≤ N ≤ 1000 N ≤ 20 in test data worth 40% of all points Sample Input(Plaintext Link) 2 ababca aaabb Sample Output(Plaintext Link) YES NO

DONUTS - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Andrii Mostovyi
Tester:Kevin Atienza
Editorialists:Pushkar Mishra and Suhash Venkatesh

DIFFICULTY:

Easy

PREREQUISITES:

Sorting, Greedy

PROBLEM:

Given chains of doughnuts of different lengths, we need to join them to form a single chain. Two chains can be joined by cutting a doughnut into two and using it to clip the chains together. We need to minimize the number of cuts needed to form a single chain consisting of all the $N$ doughnuts.

EXPLANATION:

Subtask 1
Since all the chains are of length 1, we can simply take them one by one and attach to form larger chain. Thus, the answer each time is $\lfloor\frac{M}{2}\rfloor$.

Subtask 2 and 3
We can observe that a single doughnut is capable of joining two chains of lengths $l_1$ and $l_2$ in one cut to form a chain of length $l_1 + l_2 + 1$. This hints towards a greedy solution. We need to decide the number of single doughnuts we need in order to join all the chains together. It can be noted that it is best to join longer chains together. For example, consider the case when we have chains of lengths 1, 2, 3. It is best to join chains of lengths 2 and 3 with the help of the unit-length chain. Any other order of joining doesn't yield an optimal result.

Thus, we begin by sorting the chains by their lengths. Next, we iterate from $i = 1$ to $M$. We stop at that $i$ where cumulative sum of chain lengths from 1 to $i$ becomes greater than $M-i-1$. This is the point where we have the sufficient number of single doughnuts to join all chains. As a last step, we need to check whether cumulative sum up to $i$ is exactly equal to $M-i-1$ or more than $M-i-1$. In the former case, the answer is $M-i-1$. In the latter case, it is $M-i$ because the $i^{th}$ chain will have to be attached in the end too.

COMPLEXITY:

$\mathcal{O}(M \log M)$ per test case.

SAMPLE SOLUTIONS:

Author
Tester
Editorialist

NZEC error for ABROADS.Worked for one day but still not able to get the glitch.

$
0
0

Problem Link : ABROADS

Solution Link : JAVA

Here I'm getting NZEC for Task # 0 and Task # 3.I have used the bfs approach.P array for population and D array to store the edges.I have not been able to find the reason for NZEC.Please help me.

Test cases for Abroads

$
0
0

This is my solution for The Ancient Berland Roads I am not getting why this solution is incorrect. It is passing all the test cases that I have made but I am not getting what are the test cases which my solution is not passing.

Can any one tell me why this solution is incorrect or If what could be the appropriate test cases for it. It would be a great help.

Thanks in advance.

Cannot submit solution of INSQ15_A

$
0
0

For this problem I am unable to submit the solution to INSQ15_A. It reports 404 page not found . What to do ? How should I report it to codechef ?


Would you like an automated tester program for codechef?

$
0
0

Hi all,

As a side project i'm working on a program that will let me automatically test the programs i write for a particular problem against the sample test cases given in the problem page.

This removes the need to copy paste sample test cases every time i want to test my code.

This is purely a personal project right now, and i'm building it in a way to suit my needs only. I will be integrating this with vim, the editor i use for basic development.

I would like to know how many of you would be interested in using such a program, if i get a good response, i would develop this program in such a way other people would be able to use it.

I could implement a gui to make it usable by users not used to command line, and add the ability to add our own test cases etc.

CHEQUE -- Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Misha Chorniy
Tester:Jingbo Shang
Editorialist:Pushkar Mishra

DIFFICULTY:

Easy-Medium

PREREQUISITES:

Hash-Table

PROBLEM:

Given two types of queries:
1. Add the number to the set of numbers being maintained. 2. Remove the given number from the set if it exists in it.

The numbers to be inserted/deleted are generated according to the following scheme:
$S$ = (a*$S_{i-1}$ + b) mod $2^{32}$,
where $a$ and $b$ are integers.

The sum of the numbers finally remaining in the set after all the operations is to be reported.

EXPLANATION:

Given the number of operations to be executed, i.e., $q = 10^7$, it should be clear that the insertions and deletions from the set are to be done in $\mathcal{O}(1)$. Use of STL or pre-written libraries in C++/Java can't be used since they will definitely time out because of associated overheads.

Hash Table Solution One way is to write our own hash table. Editorialist's solution provides a standard implementation of Hash-Table with chaining to handle collision. For chaining, linked list has been used in the given solution. You can read more about it over the internet.

Bitset Solution A neater and more concise solution is using Bitset. Let's think about the naive solution to this problem first. If we could simply keep an array of length $2^{32}-1$, then direct insert/lookup in the array would have been possible. The the memory constraints don't allow that big an array. However, let us look at the constraints on the number being inserted/deleted into the set. We know they lie between 0 and $2^{32}-1$, i.e., they can be represented by 31 bits. Now, we can use a smart way to index numbers. Let us keep an array of length $2^{26}$. This is perfectly fine with the memory limits. Now, for a 31 bit integer $x$, let the first 26 bits indicate the index in the array where $x$ will reside. The rest 5 bits can be encoded in a 32 bit integer since only different $2^5$ possibilities exist. Please read setter's/tester's solutions for this approach.

There is one more intricacy here: calculating $S_i$. If we use the normal $mod$ operation present in some of the programming languages, the solution will exceed time limit. This is because $mod$ is a complex operation and performing it $10^7$ times will not work. The observation is that we have to take $mod$ $2^{32}$. If we keep the data type of $S$, $a$, $b$ to be unsigned, in that case, we will not have to use $mod$ operation because the range of unsigned int is $0$ to $2^{32}-1$. Thus, if $S$ goes over $2^{32}$ it will automatically overflow around to greater than $0$. In other words, the compiler will perform the $mod$ function implicitly because of the overflow.

COMPLEXITY:

$\mathcal{O}(1)$ per insert and delete operation.

SAMPLE SOLUTIONS:

Author
Tester
Editorialist

Why do I get a SIGSEGV?

$
0
0

Why I am getting a runtime error SIGSEGV in the problem? Where I am going wrong?

Java compiler for windows xp

$
0
0

As the title said, can you give me some names of java compilers that can be downloaded and suitable for windows xp SP2. Thank you in advance :)

Approach to become Good Programmer.

$
0
0

I really want to know that whats the ideal approach for becoming a good programmer? Whats the secret to solve the Codechef questions? Any External links, online tutorials, e-books are welcome. ANY help will be appreciated. I also want to know whats the X-factor that your resume must have in order to be shortlisted for Software Developers post. What is actually required? Is it theory, is it just practice or something else?

Viewing all 39796 articles
Browse latest View live


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