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

Laddus for November Long Challenge

$
0
0

Has the laddus for NOV17 delivered or Chef is busy with other stuffs?


Codechef Rating Predictor

$
0
0

Hello everyone!

alt text

Codechef Rating Predictor

The delay in previous month rating changes + inspiration from CF Predictor and for the practice of a web-application, i tried to write a script that can predict rating changes from ongoing live contests @ Codechef.

While the actual delays in rating changes s/would be fixed, this script can help in predicting rating changes as new submissions are made, so hopefully it can be useful for Long contests :).

The script is written in nodejs and is based on open rating formulas available at this link. The code for the project can be accessed here

Website is currently hosted on Openshift free servers and has few restrictions on use. Therefore the server might be slow or not responding during the period rating changes are calculated. Currently, ratings are expected to be updated every 15 minutes

I also tested rating changes on few past contests and the predictions were accurate within an error of 2 for almost everyone except the first rank (I have no idea why first rank predictions are wrong in some contests using current formulas)

Please note that project is still in beta stage and also actual changes might differ more due to changes in ranklist after plagiarism detection

Your feedback/suggestions would be appreciated

JUNE17 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/all/

Long: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/long/

Few stats on JUNE17 Predictions. I matched ratings (All) of first 6391 users and the results were as follows:

Difference - No of users

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

There were around 40 users having difference > 50. Turns out some usernames appears to be missing in the ranklist when sorted by rank and hence they were showing as last in the prediction list.

I ran the code again after fixing the above bug and results are better now (Maximum difference is 8)

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

COOK83 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/all/

Short: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/short/

The ratings are expected to update every 5 minute

Few stats, 4811/4820 predictions (for both all and cook-off predictions) were right. Rest have diff < 3 with the exception of rating prediction of first rank in cook off. Also, as @vikasj554 pointed out, few users got rating changed after initial update. (I still need to figure out why this happened). But even after this 4794/4820 predictions were accurate.

LTIME49 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/all/

Lunchtime : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/ltime/

The ratings are again expected to update every 5 minute

JULY17 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/all/

Long : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/long/

Update frequency: 10 mins

Teams Selected for Amritapuri and Kanpur

$
0
0

How do you plan to travel between Kanpur (24th Dec) and Amritapuri(26th Dec) ?

BUYING2 - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

DIFFICULTY

CAKEWALK

PREREQUISITES

Ad Hoc

PROBLEM

You are given N banknotes { A1, A2..., AN} given by a customer to buy sweets. One sweet costs X units.

For the number of sweets the customer wants to buy, all the banknotes are supposed to be used, that is, you shouldn't be able to buy that many sweets by discarding any banknote.

What is the largest number of sweets does the customer want to buy?

QUICK EXPLANATION

Check whether the smallest value can be ignored. If it can, the answer is -1. Otherwise, the answer is the maximum number of sweets the customer can buy.

EXPLANATION

Let, S =&Sum;(i = 1 to N)Ai

Obviously, the customer can buy, at max V = floor(S / X) sweets.

  • It should be clear from the problem statement that you will always give the customer V sweets
    • Since, the statement asks you to return the maximum number of sweets he can buy by using all the banknotes.
  • All that remains to check is, whether you must use all the banknotes to buy V sweets or not.
  • I.E. you need to check if V sweets can be bought by ignoring at least one of the banknotes, which results in the customer being "Inadequate".
    • If the customer is inadequate, you must print -1.
    • Otherwise, the answer will be V.

To buy V sweets, you must use at least V * X amount of money.

Let, R = S - (V * X) = S % X, where % is the remainder (or modulo) operation.

Lemma
If there is no banknote given whose value is less than R, then the customer is adequate.
Also, if there is a banknote whose value is less than R, then the customer is inadequate.

Proof
Let us say you could ignore a banknote b.

That means,
floor((S - b) / X) = V
floor((S - b) / X) = (S - R) / X
((S - b) / X) - (((S - b) % X) / X) = (S - R) / X
R - b = (S - b) % X

Now, if b > R then the above expression is absurd; since R - b is negative and (S - b) % X is positive.

However, if b <= R then above expression is always true.

Thus, the necessary and sufficient condition for the customer to be adequate is that there is no banknote whose value is less tan or equal to S % X. The code to solve the problem will look like

M = minimum(x: x = A[i], for all i = 1 to N)
S = sum(x: x = A[i], for all i = 1 to N)
R = S % X
if R < M
    print S / X
else
    print -1

SETTERS SOLUTION

Can be found here

TESTERS SOLUTION

Can be found here

BITWISE AND(&) for Range of Numbers

$
0
0

Given two numbers L & R , Find Bitwise AND of all numbers lying between L and R inclusive Constraints 1<= L,R <= (2^32).

long long step = 1;
 while(L!=R)
    {
        L/=2; R/=2; step*=2;
    }
    printf("%lld\n",L*step);

Can anybody help me with the explanation or logic behind the above code?

ITERATIVE method instead of RECURSIVE one to solve SPOJ GSS1 question

$
0
0

I'm trying to solve the spoj GSS1 using an iterative implementation of segment trees instead of a recursive approach. I have successfully built the segment tree but I'm finding it difficult to code the query() method using an iterative approach! Can anyone help in implementing the code using an iterative approach?Link to my code

can any solve this question? only two test case passed..

$
0
0

Raja loves Strings. In Strings he specially loves palindromes.Palindromes are strings that read the same when read forward or backwards. Here Palindromes considered are only of even length(maybe 0). His Teacher gave me him a long string consisting of only digits as a gift on his birthday. Now Raja wants to know The longest subarray whose elements (i.e digits) can be rearranged to form a palindrome of even length. Raja is unable to figure out the solution to the problem so he asks for your help.

INPUT SPECIFICATION - The function contains one argument - A String S consisting of digits (0-9). First and only line of input consists of S (1 <= |S| <= 100000). OUTPUT SPECIFICATION - You must return a single integer denoting the longest subarray whose elements (digits) can be rearranged to form a palindrome of even length.If no such subarray can be found return 0. Example - Sample Test Case 1

Input

12345354987

Output

6 Explanation : No subarray can be rearranged to form even length of palindrome .Hence 0.

Explanation : Here the longest subarray is 345354 which can be rearranged to form 345543 which is a palindrome of even length 6.Hence and is 6.

Sample Test Case 2-

Input

12345

Output

0

Queries regarding On-Site for ICPC

$
0
0

Our team have qualified for both Amritapuri and Kanpur on-site round. This is our first time going for the on-site round, I have few questions:

  1. If like last year we are allowed to give both regionals at one place, would we get 2 t-shirts? or only one?
  2. Do we get 2 different certificate for both regionals or just one?
  3. Kanpur regional is on 23-24th Dec. Any idea by what time we would be free and will be allowed to leave for amritapuri. Like by what time on 24th the main competition will be over?

Please answer if you have any idea regarding this. Thanks in advance.

Also, if you have any doubt comment below, will add on this thread.


ACM ICPC 2017 Internal Error Not Resolved

$
0
0

We had participated in ACM ICPC 2017 Online Prelim Contest. Our team name was "The Dementors" and CodeChef handle was "acm17in1163". We had an internal error issue with the second question "Standard Deviation" (STDDEV). This error was not resolved for us even though we had filled the Google form which CodeChef provided after the contest. The issue was as follows:

  1. We submitted the solution to the question but it went showing an internal error.
  2. There were no instructions given by CodeChef at that point (maybe due to the site being slow).
  3. So, to know if our solution is correct or wrong we again submitted the solution but it again went for an internal error.
  4. We stopped for quite a long time, but we weren't able to receive any updates on the submission.
  5. "My Submissions" showed that the solution wasn't evaluated and it showed an internal error with on the red cross.
  6. Then we had to submit the solution for third time when we got to know that it was an incorrect solution.
  7. For the fourth time we submitted correct solution to the problem. But we had three penalties which were not resolved before the result declaration.

We not only wasted our time but also due to the wrong submissions we got massive penalties which led us not to qualify for the regional.

You can check that three of our submissions were same out of which two were involved in internal error. We had filled the Google form for that but the issue wasn't solved. Yesterday, we had our Chennai Results declared and they have even provided the total time taken by each team. Our team still has penalties for internal error issue.

I request CodeChef to resolve those issues with our team as if the penalties are resolved we get a chance to qualify to regional.

CSUBQ - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Deepjal Chhetri
Tester:Istvan Nagy
Editorialist:Oleksandr Kulkov

DIFFICULTY:

MEDIUM

PREREQUISITES:

Segment trees

PROBLEM:

You are to answer the following queries on an array (initially, all elements are zero):

  1. 1 x y - Change $x$'th element to $y$
  2. 2 l r - Count the number of subarrays $[l_1, r_1]$ of subarray $[l, r]$ (that is, $l\le l_1\le r_1\le r$), whose maximum element lies in range $[L, R]$. Numbers $L$ and $R$ are the same in all queries.

QUICK EXPLANATION:

Write the number of subarrays whose maximum element lies in the range $[L, R]$ as:

$|\{\text{subarrays with max}\in[L,R]\}|=|\{\text{subarrays with max} < R+1\}|-|\{\text{subarrays with max} < L\}|$

Observe that:

$|\{\text{subarrays with max} < X\}|=|\{\text{subarrays with all elements} < X\}|$

For $X=L$ and $X=R+1$, maintain an array whose element at position $i$ is $0$ if $a[i]\ge X$ and $1$ if $a[i] < X$. The query 2 now reduces to: "count number of subarrays on segment [l,r] consisting entirely of ones". This new problem can be solved using segment tree.

EXPLANATION:

Refer to the "Quick explanation" section for the first part of the solution. The problem is now reduced to answering the following queries for fixed $X$:

  1. 1 x y - Change $x$'th element to $y$ ($y\in\{0, 1\}$)
  2. 2 l r - Count the number of subarrays $[l_1, r_1]$ of subarray $[l, r]$ (that is, $l\le l_1\le r_1\le r$) consisting of $1$'s. Number $X$ is the same in all queries.

Use segment tree to solve this problem. In each node, store the following information:

struct Node {
    long long num_ones_subarrays;
    int len, len_ones_left, len_ones_right;
};

Here,

  1. $len$ is the length of the range $[l;r]$ represented by the node ($len=r-l+1$)
  2. $num$_$ones$_$subarrays$ is the number of subarrays consisting of ones in the range represented by the node
  3. $len$_$ones$_$left$ is the length of the largest prefix consisting of ones in the range represented by the node
  4. $len$_$ones$_$right$ is the length of the largest suffix consisting of ones in the range represented by the node

In order to solve the problem we should show that the stored information is self-sufficient, that is, we can merge two nodes and recalculate all 4 variables. So, suppose that nodes $a$ and $b$ are being merged into node $res$. Then:

  1. Length of $res$ range is the sum of lengths of ranges $a$ and $b$.
  2. The number of ones subarrays in the $res$ range can be calculated as the sum of number of subarrays lying completely in $a$ range ($a.num$_$ones$_$subarrays$), in $b$ range ($b.num$_$ones$_$subarrays$) and the number of subarrays that cross the boundary between $a$ and $b$. As the subarrays should be non-empty and should consist of ones, it is $a.len$_$ones$_$right\times b.len$_$ones$_$left$.
  3. The length of the largest prefix of ones in the $res$ range is $len$_$ones$_$left$ if there is at least one zero in the range $a$, that is, if $a.len$_$ones$_$left \neq a.len$. Otherwise, it is $a.len$_$ones$_$left+b.len$_$ones$_$left$.
  4. The length of the largest suffix is computed similarly.

This corresponds to the following Node merge code:

Node merge(Node a, Node b) {
    Node res;

    res.len = a.len + b.len;

    res.num_ones_subarrays =
        a.num_ones_subarrays +
        b.num_ones_subarrays +
        a.len_ones_right * (li)b.len_ones_left;

    res.len_ones_left = a.len_ones_left;
    if (a.len_ones_left == a.len)
        res.len_ones_left += b.len_ones_left;

    res.len_ones_right = b.len_ones_right;
    if (b.len_ones_right == b.len)
        res.len_ones_right += a.len_ones_right;

    return res;
}

The time complexity of the solution is $O((N+Q)\log N)$ from the underlying segment tree (it is possible to make it $O(N+Q\log N)$ by building the segment tree in linear time). The memory complexity of the solution is $O(N)$.

The implementation with 2 separate segment trees for different $X=L$ and $X=R+1$ is enough to get AC, yet it is possible to make it faster via combining the trees into one.

As the input is quite large, care should be taken to avoid unnecessary input lag. For example, using C++ iostreams consider adding:

ios_base::sync_with_stdio(false);
cin.tie(nullptr);

AUTHOR'S AND TESTER'S SOLUTIONS:

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

RELATED PROBLEMS:

[Tutorial] Disjoint Sparse Table

$
0
0

Introduction

Hi! Since I couldn't find a tutorial on this data structure and I decided to make one myself. I don't know if this data structure has a name so I am just using the name I saw it being referred to on codeforces i.e. Disjoint Sparse Table or DST.

So before diving into its structure and working let's talk what it supports and when can it be used

Suppose you are given an array $A$ of size $N$ and you are asked to perform $Q$ queries.
Each query asks you to compute some function $F$ over subarray $[L, R]$ i.e. $F(A_L, A_{L+1}, \cdots, A_R )$

Now with a sparse table, you can answer these queries in $\mathcal{O}(\ln N)$ with $\Theta(N \ln N)$ preprocessing.

Let $N' = 2^{\lceil \ln N \rceil}$. Then with disjoint sparse table we can answer the queries in $\Theta (1)$ with $\Theta(N' \ln N')$ preprocessing.

Note:

  • Here ln means base 2.
  • Array A is immutable
  • Function F isassociative.
  • If F isidempotent then normal sparse table can also answer queries in $\Theta(1)$

As you can see you won't need to use this DS in most problems. As problems with immutable data and with tight time constraints are very rare.

Structure

Its structure is same as a segment tree. Each node stores information related to a range of indexes $[L, R)$.

visual representation of DST

Pardon my sub-par MS paint skills.
Note: It should be depth not height in the image

Now consider a node corresponding to $[L, R)$ and the middle index $M = \frac{L+R}{2}$.
This node stores precomputed values of $$F(A[i \ldots M]) \mid i \in [L, M] \text{ and}$$ $$F(A[M+1 \ldots i]) \mid i \in [M+1, R)$$ So size of node is equal to $R-L$. If its $size>1$ then it has two children corresponding to $[L, M)$ and $[M, R)$.

Building

Now to build a node corresponding to $[L, R)$. We first compute all the required precomputed values in $\Theta(R-L)$ and recursively build its child nodes.

Let the time complexity to build a tree with root of size $X$ be $T(X)$ then $$T(X) = 2 T(^X/_2) + \Theta(X)$$ $$\Rightarrow T(X) = \Theta(X \ln X)$$

So Time complexity to build a DST is equal to $\Theta(N \ln N)$.

Querying

We can answer Queries recursively similar to how we do in segment tree. Let us say we are in node $[L, R)$ and we need to answer query corresponding to $[X, Y]$; then

if $X \le M \le Y$ then we an answer in $\Theta(1)$ provided we can merge answers of $[X, M]$ and $[M+1, Y]$ in $\Theta(1)$.

else the range $[X, Y]$ is completely in one of the child node ranges and we move the query downwards to that node.

So Time Complexity for querying would be $\mathcal{O}(\ln N)$. Note that worst case happen in cases like $X=Y= \frac {N}{2} - 1$.

Improving Time Complexity

Let's increase the size of array $A$ to $N' = 2^{\lceil \ln N \rceil}$ i.e. till its size becomes a power of 2. Note that this wouldn't change the answer to any query.Let $x =\lceil \ln N \rceil$.

Now consider the $j^{th}$ node (0-based indexing from left) at depth $i$. It's $size = \frac{N'}{2^i}$. It would correspond to $\left[ \frac{N'}{2^i}\times j, \frac{N'}{2^i}\times (j+1)\right)$. Its $M = j \times \frac{N'}{2^{i}} + \frac{N'}{2^{i+1}}$.

Consider M's binary representation. It would be of the form
$$%\underbrace{m_1m_2m_3m_4m_5 \ldots m_k}*{\text{binary representation of j}}1\underbrace{00000 \ldots0 0000}*{x-i-1 \text{ zeroes}}$$
binary representation of M

Now lets say we are asked to answer a query $[L, R]$. Removing $L=R$ trivial case we can say that $L < R$ and binary representation of L and R would be of the form:

$ \begin{matrix} L& = b_0b_1b_3 \ldots b_{k_1}& 0 & l_1 & l_2 & \ldots & l_{k_2} \\ R& = b_0b_1b_3 \ldots b_{k_1}& 1 & r_1 & r_2 & \ldots & r_{k_2} \\ \hline M& = b_0b_1b_3 \ldots b_{k_1}& 1 & 0 & 0 & \ldots & 0 \end{matrix} $

Note that $k_2 = \text{word size } - \text{number of leading zeroes of }L \oplus R - 1$.
It can be seen that $L < M \le R$. Furthermore it can be verified that a node at $depth = x - k_2 - 1$ has $M$ as its middle index. Now it remains to verify that the bounds of that node say $[X, Y]$ fully contain the interval $[L, R]$.

One can see that binary representation of $X$ and $Y$ would be as follows

$ \begin{matrix} M& = b_0b_1b_3 \ldots b_{k_1}& 1 & 0 & 0 & \ldots & 0 \\ X& = b_0b_1b_3 \ldots b_{k_1}& 0 & 0 & 0 & \ldots & 0 \\ Y& = b_0b_1b_3 \ldots b_{k_1}& 1 & 1 & 1 & \ldots & 1 \end{matrix} $

Thus $X \le L < R \le Y$.

Considering that the microprocessor has BSR(Bit Scan Reverse) operation we can determine the node, that can answer the query in $\Theta(1)$, in $\Theta(1)$.

So now each query can be answered in $\Theta(1)$.

Implementation

We can see that each level sum of sizes of nodes is equal to $N$. So We can simply use a 2 dimensional array to store DST. I will explain with an example:

Solution to range product query:

Suppose we are given an array an array $A$ and a number $P$ and we are asked to answer $Q$ queries:
given $L$ and $R$, $0 \le L \le R < N$, find $\prod\limits_{i=L}^R A_i \pmod P$.

Global variables and constants:

#define MAXN 1000000
#define MAXPOWN 1048576     // 2^(ceil(log_2(MAXN)))
#define MAXLEV 21           // ceil(log_2(MAXN)) + 1
int n, P, Q;
int A[MAXPOWN];
int table[MAXLEV][MAXPOWN];
int maxlev, size;

Then some initialisations:

size = n;
maxlev = __builtin_clz(n) ^ 31;     // floor(log_2(n))
if( (1<<maxlev) != n)
    size = 1<<++maxlev;

Then the build function(the preprocessing part):

void build(int level=0,int l=0, int r=size)
{
  int m = (l+r)/2;

  table[level][m] = A[m]%P;
  for(int i=m-1;i>=l;i--)
    table[level][i] = (long long)table[level][i+1] * A[i] % P;

  if(m+1 < r) {
    table[level][m+1] = A[m+1]%P;
    for(int i=m+2;i<r;i++)
      table[level][i] = (long long)table[level][i-1] * A[i] % P;
  }
  if(l + 1 != r)        // r - l > 1
  {
    build(level+1, l, m);
    build(level+1, m, r);
  }
}

We call build() to initialize the DST.

Now to answer query [X, Y] we use

int query(int x, int y)
{
  if(x == y)
    return A[x]%P;
  int k2 = __builtin_clz(x^y) ^ 31;
  int lev = maxlev - 1 - k2;
  int ans = table[lev][x];
  if(y & ((1<<k2) - 1)) // y % (1<<k2)
    ans = (long long)ans *  table[lev][y] % P;
  return ans;
}

Note:

  • I assume that size of int is 32 bits
  • __builtin_clz() is an inbuilt function in gcc compiler(not in C++ standard) which returns the count of leading zeroes(hence the name)
  • 31 - num = 31 ^ num. This this true for any number of the form $2^x-1$.

You can try solving SEGPROG with this DS.

Credits

Bit- Manipulation : finding subset

$
0
0

What is the logic behind finding subset using bit manipulation?

Here's the code:-

for(counter = 0; counter < pow_set_size; counter++) { for(j = 0; j < set_size; j++) {

      if(counter & (1<<j))
        printf("%c", set[j]);
   }
   printf("\n");
}

source :- http://www.geeksforgeeks.org/power-set/

CHEFPATH - editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Prateek Gupta
Tester:Sergey Kulik
Editorialist:Mugurel Ionut Andreica

DIFFICULTY:

SIMPLE

PREREQUISITES:

Hamiltonian Path, Hamiltonian Cycle

PROBLEM:

Given an NxM maze, find out if there is a path starting at some cell (a,b), passing through all the cells of the maze and then ends in a cell (c,d) which is adjacent to the starting cell (i.e. they have a border in common). Along the path one can move from the current cell only in one of the 4 directions (up, down, left, right).

QUICK EXPLANATION:

Since the ending cell must be adjacent to the starting cell, the found path can be immediately extended one more step, into a cycle which passes through all the cells of the maze. Such a cycle is called a Hamiltonian cycle. Note that in this case it doesn't matter which is the starting cell.

An NxM maze has a Hamiltonian cycle if and only if:

  • min{N,M}=1 and max{N,M}=2, OR
  • min{N,M}>=2 and at least one of N and M is even.

EXPLANATION:

If N=1 or M=1, and max{N,M}>=3 it is obvious that no Hamiltonian cycle exists in the maze (because the cells at the endpoints only have one neighbor). However, a solution does exist when min{N,M}=1 and max{N,M}=2 (the two cells are adjacent to each other).

Let's now consider the case min{N,M}>=2 and at least one of N or M is even. Let's assume now that N is even (if it's not then M must be even, so we just swap the values of N and M between them). We can start the cycle at the cell (1,1), then move right to (1,M). From there we move down to (2,M) and then left to (2,2). From (2,2) we move down to (3,2), right to (3,M), then down to (4,M) and left to (4,2). We continue this procedure until we reach the cell (N,2). From here we move left to (N,1) and then all the way up to (1,1).

AUTHOR'S AND TESTER'S SOLUTIONS:

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

CHDOGS - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

simple

PREREQUISITES

symmetry, rate of approach, trigonometry

PROBLEM

There are three points on equilateral triangle of side $s$. Each point is moving constant velocity $v$ towards the point on the right of it. You need to find the time at which these three points will meet.

QUICK EXPLANATION

The answer is $\frac{2}{3} \frac{s}{v}$.

EXPLANATION

This question can be solved in a lot of the ways. Actually, this problem was easily search-able on web. The intent of giving this problem was to familiarize the readers with various different ways of solving the problem.

Where will the points meet?

By symmetry, we can say that the points will meet at the centroid of the triangle. In fact, the triangle formed by the three points at any install during their journey will also stay equilateral.

Velocity of approach based solutions.

Let us consider the points $A, B, C$, at some instant. The point A is moving towards $B$. $B$ is moving towards $C$, and $C$ towards $A$. Let us find our rate of approach of points $A$ and $B$ towards each other. $A$ is moving towards $B$, so its velocity vector $v$ will contribute completely in the rate of approach. Velocity vector of $B$ is directed towards $C$, so its component $v cos(60)$ towards $A$ will only contribute in the rate of approach. So rate of approach of $A$ and $B$ towards each other will be $v + v cos(60) = \frac{3 v}{2}$.

By symmetry, we can say that rate of approach will be same for $A, B$, $A, C$ and $B, C$ all three pairs.

Initially the distance between $A, B$ is $s$. So, total time taken in meeting will be

$$\frac{s}{\frac{3 v}{2}} = \frac{2 s}{3 v}$$

You can also see this beautiful written answer on stackexchange too.

By solving the expression for separation vs time

You can solve this question by rigorously working out expressions of separation vs time. This solution can be found here.

Simulation based solution

You can say that the time will be proportional to side of equilateral triangle $s$, inversely proportional to speed.

$$t \propto \frac{s}{v}$$ The proportional relation should not depend on values of $s$ and $v$, so it will be a constant. $$t = c \cdot \frac{s}{v}$$

Finding the constant $c$ can be done experimentally by a simulating the motion of points by taking $dt$ (change in time) as low as possible. You will see that the constant will approach towards $\frac{2}{3}$.

Interesting readings.

This Stackexchange answer very beautifully explain finding the location of meeting of points without using the symmetry argument directly.

In the same context, this answer is also worth reading.

This Quora answer gives an idea of solving the problem for any general regular polygon.

Time complexity of all these solutions at the end are constant time ($\mathcal{O}(1)$.

EDITORIALIST'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Can be found here.

cutting receipe


Help in MARCHA1

how to solve SSHUFLE on spoj

$
0
0

i coded this question using 3-D dp approach but get weird ans for sample test cases. please help. problem link:link text code link:link text

Not getting AC in hackerearth's Subarray-Function?

$
0
0

I am solving This problem from hackerearth, Unfortunately my code is not passing the two test cases, please suggest me how do I optimize it further so that I can pass all the test cases.

link to my code -> My Code

COPS - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Devendra Agarwal
Tester:Surya Kiran
Editorialist:Amit Pandey

DIFFICULTY:

Cakewalk

PREREQUISITES:

None

PROBLEM:

There are 100 houses in a lane, numbered from 1 to 100. N cops are positioned in some houses. A cop's running speed is $h$ houses per second and he can run for at max $t$ secs. Find number of houses where a thief can hide such that he won't be caught by any of the cops.

QUICK EXPLANATION:

For each house and each cop, we can check whether the cop can reach the house or not by checking whether distance between them is less than or equal to maximum distance a cop can travel ($h * t$). If some cop can reach a house, then the house is unsafe otherwise it is safe.

The editorial explains three methods of finding number of safe houses having time complexities of $\mathcal{O}(H N)$, $\mathcal{O}(H \, log N)$ and $\mathcal{O}(H + N)$ respectively, where $H$ denotes number of houses (is fixed to 100 in our problem) and $N$ denotes the number of cops.

Explanation

For a particular house, we want to find out whether this house can be checked by some cop or not. We know that a cop can cover a maximum of $h * t$ inter-house distances in $t$ secs. So, if the distance between the thief's hiding house and cop's house is less than or equal to $h * t$, then the cop can catch the thief. We just need to check whether the current house can be reached by any of the cops or not. If yes, then it is not safe otherwise it is safe.

So, we can describe the solution succinctly as follows.

ans = 0
for each house from 1 to 100:
    safe = true
    for each cop houses from 1 to N:
       if (the cop can reach the house)
          safe = false
    if (safe) ans += 1

Clearly the above implementation of the problem will take $\mathcal{O}(100 * N)$ time.

Faster Solution

Let us say thief is currently at house $p$ and we want to check whether he will be safe in this house or not. If we can find the nearest cops in both directions of the lane from current house, then we just need to check whether these nearest cops in either direction can reach the house $p$ in time or not.

We will describe a method for finding nearest cop in forward direction faster than $\mathcal{O}(N)$ time. Backward direction can be handled similarly.

Let us can create a sorted array of houses of cops. We want to find the first element in the array having value $\geq p$. This can be done by using binary search over the array. Time complexity of this will be $\mathcal{O}(N)$ per search operation in array.

You can also find the same thing using $\mathtt{lower}$_$\mathtt{bound}$ in set in C++. set maintain a balanced binary search tree underneath it, which takes $\mathcal{O}(log N)$ time for each $\mathtt{lower}$_$\mathtt{bound}$ query.

So, this solution runs in $\mathcal{O}(100 * log N)$ time. Can we make it faster?

Even Faster Solution

We have to find $nextCopHouse$/$prevCopHouse$ information for each house faster. Let us see how can find $nextCopHouse$ information faster. Let us make a boolean array $isCop$ of size $100$ where $isCop[i]$ denotes that there is a cop in $i$-th house or not.

Now, we go from house number 100 to 1 and update the $nextCopHouse$ information by maintaining the position of latest house having cop in it.

latestHouseHavingCop = -1;
for house p from 100 to 1:
    if (there is a cop in the house):
        latestHouseHavingCop = p;
    nextCopHouse[p] = latestHouseHavingCop;

Time complexity of this solution is $\mathcal{O}(N + 100)$.

AUTHOR'S, TESTER'S SOLUTIONS:

setter's solution
tester's solution

Where to register and pay for KGP onsite regionals?

$
0
0

The Baylor site states that registration for KGP opens on 31st Dec, whereas the onsite contest is on 16-17 Dec'17. Can anyone please provide further details on its registration and last dates?

Viewing all 39796 articles
Browse latest View live


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