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

LEBOMBS - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

DIFFICULTY:

Cake walk

PREREQUISITES:

None

PROBLEM:

You're given an array of houses some of which have a bomb and others don't. These bombs will explode simultaneously and when bomb in ith house explodes, it destroys adjacent houses. Your task is to find out the number of houses which aren't destroyed.

QUICK EXPLANATION:

For every house check if it is destroyed or not.

DETAILED EXPLANATION:

There are two almost similar ways of solving this problem. Key idea is to find out for each house if it is destroyed or not. How do we check if ith house will be destroyed or not? It will be destroyed iff at least one of i-1, i and i+1th houses have a bomb. Just beware of the boundaries as first and last houses have only one adjacent house. So final solution is :

saved_count = 0
for i from 1 to N
    destroyed = false
    if( S[i] == '1') destroyed = true
    if( i > 1 and S[i-1] == '1') destroyed = true
    if( i < N and S[i+1] == '1') destroyed = true
    if( not destroyed)
        saved_count += 1
print saved_count

An alternative solution would be to move over houses with bombs and mark those houses that will explode.

bool will_be_destroyed [N]
fill( will_be_destroyed, false)

for i from 1 to N
    if S[i] == '1'
        will_be_destroyed[i] = true
        if(i > 1) will_be_destroyed[i-1] = true
        if(i < N) will_be_destroyed[i+1] = true

saved_count = 0
for i from 1 to N
    if(not will_be_destroyed[i])
        saved_count += 1

print saved_count

Both of these are O(N) solutions and very comfortably fit in time limit.

SETTER'S SOLUTION:

Will be uploaded soon.

TESTER'S SOLUTION:

Can be found here.


GOODBAD - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

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

PROBLEM

You just received a message given by a string $s$. You don't know whether this message is sent by Chef or his brother. Also, the communication channel through which you received the message is erroneous and hence can flip a letter from uppercase to lowercase or vice versa. However, you know that this channel can make at most $k$ such flips.

Chef always sends messages to his friends in all small letters, whereas the little brother sends messages in all capital letters. Determine whether the message could have been sent only by Chef, only by the little brother, by both or by none.

EXPLANATION

Number of uppercase letters <= $k$ implies that it could have been Chef. This is because we can consider all the uppercase letters as "flips" made by the communication channel, which would imply that our original message comprised only of lowercase letters. Similarly, number of lowercase letters <= $k$ implies that it could have been Chef's brother. Here is the implementation in Python:

t = int(input()) for _ in range(t): (n, k) = list(map(int, input().split(' '))) s = input() chef = sum([1 for ch in s if ch >= 'A' and ch <= 'Z']) <= k brother = sum([1 for ch in s if ch >= 'a' and ch <= 'z']) <= k if (chef and brother): print("both") elif (chef): print("chef") elif (brother): print("brother") else: print("none")

AUTHOR'S AND TESTER'S SOLUTIONS:

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

Data Structures and Algorithms

$
0
0

Hi all, I need your help to make a list of most used data structures and algorithms along with their tutorials, implementation and some problems on them. It will be helpful to everyone in many ways. I request everyone to contribute to this list by providing links to tutorials, problems, etc. I will keep updating this list regularly.

  1. Binary Search :Tutorial, Problems, Tutorial, Implementation, Problem

  2. Quicksort :Tutorial, Implementation, Tutorial

  3. Merge Sort :Tutorial, Implementation, Tutorial

  4. Suffix Array :Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem

  5. Knuth-Morris-Pratt Algorithm (KMP) :Tutorial, Tutorial, Implementation, Tutorial, Problem

  6. Rabin-Karp Algorithm :Tutorial, Implementation, Tutorial, Problem, Problem

  7. Tries :Tutorial, Problems, Tutorial : I,II, Tutorial, Problem, Problem, Problem

  8. Depth First Traversal of a graph :Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem

  9. Breadth First Traversal of a graph :Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem, Flood Fill

  10. Dijkstra's Algorithm :Tutorial, Problems, Problem, Tutorial(greedy), Tutorial (with heap), Implementation, Problem, Problem

  11. Binary Indexed Tree :Tutorial, Problems, Tutorial, Original Paper, Tutorial, Tutorial, Problem, Problem,Problem, Problem, Problem, Problem, Problem

  12. Segment Tree (with lazy propagation) :Tutorial, Implementation, Tutorial, Tutorial, Problems, Implementation, Tutorial, Implementation and Various Uses, Persistent Segment Tree: I, II, problems same as BIT, Problem, Problem/HLD is used as well/

  13. Z algorithm :Tutorial, Problem, Tutorial, Tutorial, problems same as KMP.

  14. Floyd Warshall Algorithm :Tutorial, Implementation, Problem, Problem

  15. Sparse Table (LCP, RMQ) :Tutorial, Problems, Tutorial, Implementation(C++), Java implementation

  16. Heap / Priority Queue / Heapsort :Implementation, Explanation, Tutorial, Implementation, Problem, Chapter from CLRS

  17. Modular Multiplicative Inverse

  18. Binomial coefficients (nCr % M): Tutorial, Tutorial, Paper, Problem

  19. Suffix Automaton :Detailed Paper, Tutorial, Implementation (I), Tutorial, Implementation (II), Problem, Problem, Problem, Problem, Tutorial, Implementation

  20. Lowest Common Ancestor :Tutorial, Problems, Paper, Paper, Problem, Problem, Problem

  21. Counting Inversions :Divide and Conquer, Segment Tree, Fenwick Tree, Problem

  22. Euclid's Extended Algorithm

  23. Suffix Tree :Tutorial, Tutorial, Intro, Construction : I, II, Implementation, Implementation, Problem, Problem, Problem, Problem

  24. Dynamic Programming : Chapter from CLRS(essential), Tutorial, Problems, Problem, Problem, Problem, Problem, Tutorial, Problem, Problem, Problem, Longest Increasing Subsequence, Bitmask DP, Bitmask DP, Optimization, Problem, Problem, Problem, Problem, Problem, Problem, Problem, DP on Trees : I, II

  25. Basic Data Structures :Tutorial, Stack Implementation, Queue Implementation, Tutorial, Linked List Implementation

  26. Logarithmic Exponentiation

  27. Graphs :Definition, Representation, Definition, Representation, Problem, Problem

  28. Minimum Spanning Tree :Tutorial, Tutorial, Kruskal's Implementation, Prim's Implementation, Problem, Problem, Problem, Problem, Problem

  29. Efficient Prime Factorization

  30. Combinatorics :Tutorial, Problems, Problem, Tutorial

  31. Union Find/Disjoint Set :Tutorial, Tutorial, Problems, Problem, Problem, Problem

  32. Knapsack problem :Solution, Implementation

  33. Aho-Corasick String Matching Algorithm :Tutorial, Implementation, Problem, Problem, Problem, Problem

  34. Strongly Connected Components :Tutorial, Implementation, Tutorial, Problem, Problem, Problem

  35. Bellman Ford algorithm :Tutorial, Implementation, Tutorial, Implementation, Problem, Problem

  36. Heavy-light Decomposition :Tutorial, Problems, Tutorial, Implementation, Tutorial, Implementation, Implementation, Problem, Problem, Problem

  37. Convex Hull :Tutorial, Jarvis Algorithm Implementation, Tutorial with Graham scan, Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem

  38. Line Intersection :Tutorial, Implementation, Tutorial, Problems

  39. Sieve of Erastothenes

  40. Interval Tree :Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem, Problem, Tutorial

  41. Counting Sort

  42. Probabilities

  43. Matrix Exponentiation :Tutorial, Tutorial

  44. Network flow :(Max Flow)Tutorial : I,II, Max Flow(Ford-Fulkerson) Tutorial, Implementation, (Min Cut) Tutorial, Implementation, (Min Cost Flow)Tutorial : I,II,III, Dinic's Algorithm with Implementation, Max flow by Edmonds Karp with Implementation, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem

  45. K-d tree :Tutorial, Tutorial, Implementation, Problem

  46. Deque

  47. Binary Search Tree :Tutorial, Implementation, Searching and Insertion, Deletion

  48. Quick Select :Implementation, Implementation

  49. Treap/Cartesian Tree :Tutorial(detailed), Tutorial, Implementation, Uses and Problems, Problem, Problem

  50. Game Theory :Detailed Paper, Tutorial, Problems, Grundy Numbers, Tutorial with example problems - I,II,III,IV, Tutorial, Problems, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Nim

  51. STL (C++) :I,II, Crash Course

  52. Maximum Bipartite Matching

  53. Manacher's Algorithm :Implementation, Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem, Problem

  54. Miller-Rabin Primality Test : Code

  55. Stable Marriage Problem

  56. Hungarian Algorithm, Tutorial

  57. Sweep line Algorithm : I, II

  58. LCP :Tutorial, Implementation, Tutorial, Implementation

  59. Gaussian Elimination

  60. Pollard Rho Integer Factorization, problem

  61. Topological Sorting

  62. Detecting Cycles in a Graph : Directed - I, II Undirected : I

  63. Geometry : Basics, Tutorial

  64. Backtracking :N queens problem, Tug of War, Sudoku

  65. Eulerian and Hamiltonian Paths :Tutorial, Tutorial, (Eulerian Path and Cycle)Implementation, (Hamiltonian Cycle)Implementation

  66. Graph Coloring :Tutorial, Implementation

  67. Meet in the Middle :Tutorial, Implementation

  68. Arbitrary Precision Integer(BigInt), II

  69. Radix Sort, Bucket Sort

  70. Johnson's Algorithm :Tutorial, Tutorial, Implementation

  71. Maximal Matching in a General Graph :Blossom/Edmond's Algorithm, Implementation, Tutte Matrix, Problem

  72. Recursion : I,II, Towers of Hanoi with explanation

  73. Inclusion and Exclusion Principle : I, II

  74. Co-ordinate Compression

  75. Sqrt-Decomposition :Tutorial, Tutorial, Problem, Problem

  76. Link-Cut Tree :Tutorial, Wiki, Tutorial, Implementation, Problem, Problem, Problem, Problem

  77. Euler's Totient Function :Explanation, Implementation, Problems, Explanation, Problems

  78. Burnside Lemma :Tutorial, Tutorial, Problem

  79. Edit/Levenshtein Distance :Tutorial, Introduction, Tutorial, Problem, Problem

  80. Branch and Bound

  81. Math for Competitive Programming

  82. Mo's Algorithm : Tutorial and Problems

MINMAX2 - EDITORIAL

$
0
0

Minimum Maximum Partition

Problem Setter:Istasis Mishra

Problem Tester:Istasis Mishra

Editorialist:Taranpreet Singh

Problem:

Given two arrays P and Q of Size N and an integer K, Minimize AND maximize the cost of partitioning the range [1...N] into exactly K partitions, where cost of a partition is defined as $min(P[L...N])*max(Q[1...R])$.

Prerequisites:

Dynamic Programming - Convex Hull Optimization or Divide and Conquer Optimization(But don't worry, its not as hard as it sounds)

Solution:

Since We have cost of a partition defined as $min_{L \leq i \leq N}(P[i]) \times max_{1 \leq i \leq R}(Q[i])$, we can observe that min(P[L....N]) = min(P[L], P[L+1....N]) and max(Q[1...R]) = max(Q[1...L-1], Q[L]). This means that we can pre-calculate min(P[i..N]) as well as max(Q[1...i]) for 0<=i<=N-1.

Now, The most complicated part of this problem is that, both P and Q can also have negative values, implying that in case both min(P[L..N) and max(Q[1..R]) are negative, we may still have positive cost, thus, have to be considered for Maximum solution, otherwise if there were only positive values then there is a nice greedy solution to this.

Now, to get the correct solution that receives 36 points, there is a recurrence. Let us define a function $F$ such that $F(i, k) = \text{Making k partitions till i}$. Defining the states like this gives the clear recurrence that $F(i, k) = min_{1 \leq j \leq i}(F(j, k-1) + A[j] \times B[i])$ where A[j] is the pre-computed value of min of all P from j to N and B[i] is the max of all Q from i to N. Using this as DP, we see that we have to traverse for each i, j and k and this is an $O(N^2 \times K)$ solution and gives 36 points.

We need to optimize it, and for that, it would require us the knowledge of Convex Hull Optimization. As we can see the Dp is of the form $y = m \times x + c$.

Basically, Convex hull deals with a set of lines with slope m and y-intercept, arranged on basis of slope in a stack, Speeding up selection of j in above recurrence to O(logN) time by use of binary search, giving us a total runtime of O(N^2*logN) which will easily pass the Time Limit.

The dp optimization mentioned above is usually used once, but in our problem, we are going to maintain K hulls one for each layer of DP. As you can see, if we treat the DP as having K layers then each layer depends on the previous layer. Thus, we can see that for each k we have to calculate the answer from k-1 and then add all the calculated “lines” in the current iteration to the stack.

Also, we can see that for min we require the “slope” to be decreasing and to find the min we want the slope to be increasing. Even though, this problem can be solved using a dynamic convex hull, this could be overcome by changing the DP to be calculated from N to 1 instead of 1 to N and also changing what represents the slope and the $x$. For more details, refer to the setters implementation below.

Now, to incorporate negative values and also accommodate for equal slopes, changes are required to be made in bad function (Refer code of Acquire problem here.

Also, one of the user solved this problem using divide and Conquer optimization. Here's the link to submission.

PS:Sorry for delay, its kinda hard writing editorial for a problem you yourself haven't solved yet.

Setter's solution

C++ Implementation

Java Implementation

How to forward declare variables in Python

$
0
0

I would like to know how to forward declare variables in Python. I have attached a program here. Please if anyon e has time please look at it. It is a pizza ordering program. SGST and CGST are taxes in my country. I have added the taxes to the final price and it is printing the final price as well. But I want to print SGST & CGST individually ( CGST = SGST = 2.5% of final price ). Please help me if you know.

CGST = 0.025 SGST = 0.025

View Content

How to get rid of getting NZEC error while submitting solution in java?

$
0
0

To all who are geting NZEC, try using this format in java:

import java.io.*;
import java.util.*;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        try{
            //Your Solve
        }catch(Exception e){
            return;
        }
    }
}

"I want to ask a question" - Ask them all here!

$
0
0

Hello guys,

As you all are aware, many times there are genuine users who wish to ask a question, but dont have karma for it. They then, have to resort to means of either asking their question in other threads, or request someone to upvote them so they can ask a question.

As we have seen last month, some fake accounts were used in malpractices in discuss, and they also gained karma by "I want to ask a question" thing. Hence, now it is becoming increasingly difficult to differentiate between genuine users, and fake users.

This thread is my solution for it. Any user, with less than 3 karma who wants to ask a question is requested to ask it here, and if the question is upto standards (meaning it needs more than those "one line answers") then we (at least I ) will convert your "answer" here into a question.

In short, post your question here, and if its a good genuine question, it will get posted as a separate question by using "Convert to question" feature.

In case your question required only 1 line answers or such, we would comment it on your question.

You guys are requested to direct any such guy (who wants to ask a question) here and not "free-upvote" them, so that we can avoid any duplicate/irrelevant questions (as questions posted here would be verified first, before converting to question).

Note to @admin - We will require your active participation and help in events related to deletion of any spam content here. Also, since only admins are ones who could delete answers, it is requested that you keep an eye out on this thread.

With Regards

Vijju123

Invitation to ACM-ICPC Asia-Kharagpur Onsite Replay Contest

$
0
0

Hearty Greetings!

I invite you to participate in the ACM-ICPC Asia-Kharagpur Onsite Replay Contest, which will feature the same problem sets faced by contestants at the ICPC 2017 onsite regionals.

Contest Details:
Time: (Saturday) 13th January 2018 00:00 hrs — 14th January 02:00 hrs Indian Standard Time — +5:30 GMT) — Check your timezone.
Contest link:https://www.codechef.com/KGP17ROL
Registration: You need to have a team and a CodeChef handle to participate.
Team Registration Link: https://www.codechef.com/teams/register/KGP17ROL.

For all those who are interested and do not have a CodeChef handle, are requested to register in order to participate.

Good Luck!
Hope to see you participating!


INOI 2018 discussion

Need help with a point update and range query question

$
0
0

Given an array of 'N' integers, I need to perform two kinds of queries :

  1. Point update : U P : Arr[u] = P
  2. Given a L,R,P I need to find the smallest number in the range [L,R] that is greater than P.

There are 'Q' queries.

This question was in a Hiring challenge on Hackerearth (Challenge is over now) so I can't provide a link to the statement. I want to know if this problem can be solved with complexity better than Q*Log^2N

help in bit manipulation question!

Programming Contest Detailed Syllabus Along with Example Problems

$
0
0

Competitive Programming Syllabus

Note that in general, the syllabus for Competitive Programming is open-ended. For ACM ICPC, the syllabus is not mentioned anywhere, whereas IOI syllabus is specified before the start of the contest each year. The below syllabus is kind of detailed topics from which you may face questions in competitive programming related competitions.

Geometry

String Algorithms

Substring search

Suffix Arrays

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

Suffix Trees

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

Other

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

Multi-dimensional pattern matching

Graphs

Basic Graphs

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

Flow networks/ matching

Dynamic Programming.

Greedy

Number Theory

Modulus arithmetic

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

Chinese remainder theorem

Primality tests

GCD using euclidean method

Logarithmic Exponentiation

Integer Factorization

Other

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

Probability

Counting

Special numbers

Advanced counting techniques - Polya counting, burnsides lemma

Game theory

Linear Algebra

Matrix Operations

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

Solving system of linear equations

Using matrix exponentiation to solve recurrences

Eigen values and Eigen vectors

Polynomials

Permutation cycles

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

Group Theory (Advanced Techniques)

Generating functions

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

Data Structures

Basic

Singly/Doubly Linked List

Hash Tables

Circular linked list / queue

Binary/n-ary trees

Heaps

Trie

Interval trees / Segment Trees

Fenwick (Binary Indexed) trees

Disjoint data structures

Range minimum Query (RMQ)

Customized interval/segment trees (Augmented DS)

AVL Trees

Miscellaneous

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

Exercices

Persistent Segment Tree

Centroid Decomposition

Heavy Light Decomposition

Search Techniques/Bruteforce writing techniques/Randomized algorithms.

Backtracking (beginner)

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

Dancing Links and Algorithm X given by Knuth (advanced)

Binary Search (beginner)

Ternary Search (intermediate)

Meet in the middle (Intermediate)

Hill Climbing (Advanced)

Simulated Annealing (Advanced)

Regular Iteration to reach a fixed point (Advanced)

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

Representing sets with bitmasks and manipulating bitmasks (Beginner)

General programming issues in contests

References:

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

AREAFIGR - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

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

PROBLEM

There is an equilateral triangle $ABC$ with side length $2 \cdot a$. The coordinates of the triangle's vertices are $A = (-a, 0), B = (a, 0), C = (0, \sqrt{3} \cdot a)$. Next, there are three circles with centers at the midpoints of sides $AB$, $BC$ and $AC$ and radii $r_1$, $r_2$ and $r_3$ respectively. Compute the area of the intersection of the triangle and the three circles. The absolute or relative error should be atmost $0.05$ and $a \le 50$.

EXPLANATION

First, we note that the desired accuracy for this problem isn't as high as typical geometry problems. Additionally, $a$ is quite small as well. This suggests that we can use a monte-carlo or sampling based solution to approximate the answer with reasonable accuracy. Indeed, it turns out that this is one of the easiest ways to solve this problem.

Solution One: Breaking into Rectangles

The first solution (and probably the simplest) would be to partition the triangle into a bunch of really tiny rectangles whose areas sum up to give a good enough approximation of the area of the triangle. We can then iterate over each such tiny rectangle and check whether it lies within the three circles, and if so, add up that area. It turns out that using $0.01 \times 0.01$ rectangles gives a good enough approximation for this problem.

To implement this, we can use the most brute force method possible. Since the area is bounded by $4400$ units, we won't need more than $4400 \cdot 10^4 = 4.4 \times 10^7$ rectangles. Further, checking if a rectangle is valid can be done in $O(1)$ since we just need to check if a point lies inside three circles. Thus overall, this method is fast enough.

Solution Two: Monte Carlo Based Simulation

Monte Carlo based solution Uniformly sample the points inside a triangle and check whether they belong to the three given circles. You need around $10^7$ (or $5 * 10^6$) samples to get the desired accuracy.

For checking how to uniformly sample the points in an equilateral triangle, see the http://mathworld.wolfram.com/TrianglePointPicking.html. The basic idea is as follows. Let OAB be the triangle where O is at the origin. Now, consider the vector OA and OB. Generate two numbers a, b in the range $[0, 1]$ and the OC be the vector $a * OA + b * OB$. Note that point C is uniformly generated in the parallelogram made by OABD (where point D is such that BD is parallel to OA). If the point C doesn't lie in the parallelogram, then we reflect it across the diagonal AB. This way, the point C will be a uniformly random point inside the triangle.

Another possible way could be sampling from a disk whose radius can be found as follows. Find the centroid D of the triangle. Find the radius R that is the distance between D and any of the vertices A, B, C. Now, randomly sample from a disc of radius R and check whether the point lies in each of the circles and the triangle. This method requires around $10^6$ or more queries to get a good enough accuracy.

Solution three: Misha's deterministic solution

There is a deterministic sweep line solution where you can move across the intersecting points and get the corresponding areas by using simple formulas.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

MANCBST - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

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

PROBLEM

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

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

Constraints: $n \le 10^5,$ $\text{test cases} \le 10^5.$

Print the answer modulo $663224321$ i.e. $2^{19} \times 5 \times 11 \times 23 + 1$.

PREREQUISITES

Knowledge of "online" FFT trick.

EXPLANATION

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

An $O(n^2)$ Solution

We use a dynamic program similar to "count number of BSTs having $n$ nodes". Define $T(n)$ to be number of semi-BSTs of size $n$. To find a recurrence for $T(n)$, we will iterate over the number of nodes in the left subtree. Note that fixing the number of nodes in the left subtree determines the value of the root. Suppose we say that the left subtree has $i$ nodes. Then, the number of labeled trees with $i$ nodes is $i^{i - 2}$ by Cayley's Formula. Thus, the number of ways for us to choose a left subtree is $i \times i^{i - 2} = i^{i - 1}$ since we have $i$ choices for the root of the left subtree as well. By definition, the right subtree can be chosen in $T(n - 1 - i)$ ways. Note that these two are independent, making our recurrence:

$T(n) = \sum_{i = 0}^{n - 1} (i^{i - 1} \times T(n - 1 - i))$ with base cases $T(0) = T(1) = 1$.

Clearly, there are $O(n)$ states, and it takes $O(n)$ to compute each state. Therefore, this solution is $O(n^2)$.

Speedup using Online FFT

It turns out that we can speed up the above dynamic program using a trick known as online FFT. The special modulo would have given this hint as well! For reference, please solve this Codeforces problem. The editorial for this problem explains this trick!

Additionally, you can check out these brilliant slides written by Tanuj Khattar! Interestingly, his team TooWeakTooSlow were the only team to solve this problem in the onsite regional.

The final complexity would be $O(n \log^2{n})$.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

Discrepancy in Nov long


Help in Obtain Desired Expected Value

$
0
0

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

Codechef Rating Predictor

$
0
0

Hello everyone!

alt text

Codechef Rating Predictor

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

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

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

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

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

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

Your feedback/suggestions would be appreciated

JUNE17 Links:

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

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

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

Difference - No of users

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

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

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

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

COOK83 Links:

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

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

The ratings are expected to update every 5 minute

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

LTIME49 Links:

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

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

The ratings are again expected to update every 5 minute

JULY17 Links:

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

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

Update frequency: 10 mins

ABROADS - Editorial

$
0
0

Problem Link:

Practice
Contest

Difficulty:

Medium

Pre-requisites:

Disjoint Set Union

Problem:

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

Explanation:

Solution for the subtask 1 (21 points):

The solution of this subtask is to use breadth first search after applying each query to find all the regions' city sets. If we have all the regions' cities sets, we can easily find the maximal populated region.

Let's describe this approach in more details.

Let's denote:

1) Integer array $P$, where $P[i]$ is the population of city numbered the $i$th.

2) Boolean array $D$, where $D[j]$ is true, if the road numbered the $j$th has been destroyed, and false otherwise.

3) Adjacency list $Adj$. We can store this list efficiently, for example, using STL vector in C++. For every adjacent node, let's store a structure, containing the following fields:

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

Having all this, we can process the queries in the following way:

  • P $x$ $y$ - change the population of the city numbered the $x$th to $y$. In this case, we just make a single assignment: $P[x]$ = $y$. This operation is performed in $O(1)$.

  • D $x$ - destroy the road numbered the $x$th. Again, this is just a single assignment ($D[x]$ = true), so it is also performed in $O(1)$.

Now, how to find the size of the maximal populated region.

We will make use of queue data structure.

Let's iterate through all the nodes. Whenever we find a node which was not included in any connected component, we start the breadth first search. Let's describe it in brief:

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

Let's denote Boolean array $Used$, where $Used[i]$ is true, if $i$th city was added to queue, and false otherwise.

The pseudocode of the algorithm for finding the size of the most populated region is given below.

ans = 0; For i := 1 to N used[i] = false For i := 1 to N if not used[i] queue.add(i); population = 0; while queue is not empty do curNode = queue.pop(); population += P[curNode]; For j := 0 to Adj[curNode].Length if ((not D[Adj[curNode][j].edge]) and (not Used[Adj[curNode][j].node])) Used[Adj[curNode][j].node] = true; queue.add[Adj[curNode][j].node]; ans = Max(ans, population); return ans

The complexity is $O(Q*(N+M))$.

Solution for all subtasks:

We will use the data structure called Disjoint Set Union.

Let's have $N$ elements numbered $1$ to $N$ and $N$ sets. Initially, the $i$th set contains the $i$th element.

Disjoint Set Union maintains two basic operations:

1) Uniting two sets.

2) Finding the set containing the given element.

The amortized time per operation is $O(\alpha(N))$, where $\alpha(N)$ is less than $5$ for all remotely practical values of $N$.

Note that you don't have to output the size of the most populated region before reading the next query. So, you can read all the queries in advance and solve the task in reverse order.

Assume that all $Q$ queries were performed. Let's add all connected components (regions) to the DSU. Obviously, we can determine the most populated region.

Let's create the DSU with $N$ elements denoting the cities and $N$ sets denoting the regions. Along with each set (say, the $X$th), let's maintain the value of $P[X]$, denoting the total population of the cities in the $X$th set. Now, the DSU corresponds to the road system with $N$ cities, given populations and without roads. Note that we should take the populations that are obtained after the performing of all the queries.

Now, assume that all the queries has already been performed. Then, there is a set of roads, which has not been deleted. Let's add all of them. The addition of the road is simply merging two corresponding sets in the DSU structure. Since we have one non-standard operation here, namely, handling the sizes of the regions, letТs give a pseudocode for it.

Given that we need to add a road connecting the city numbered the $X$th and the city numbered the $Y$th.

Merge (X, Y) setX = FindSet(X) setY = FindSet(Y) if (setX == setY) return; SetParent(setY, setX) P[setX] = P[setX] + P[setY]

Now, let's "rollback" the queries starting with the last one. The "rollback" of the change population query is changing the value of the corresponding $P[X]$, and the "rollback" of the road deletion query is adding the road like we've described above.

Meanwhile, we can also maintain a priority queue of an STL set for determining the size of the largest region quickly. This way, we can answer on the maximal region population in $O(\log N)$.

The complexity is O($N + M \alpha(N) + Q \log N$).

Setter's Solution:

Can be found here

Tester's Solution:

Can be found here

Getting WA in BTAR

$
0
0

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

Problem

My solution

Will CodeChef provide test cases

$
0
0

It would be very good if CodeChef could provide a detailed set of test case for a given problem and at what particular test case did a particular code fail. This would be a really good initiative on your part to help people in improving the tiny small errors that are really-really hard to spot and are often committed and never spotted.

Viewing all 40121 articles
Browse latest View live


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