ad-hoc,implementation
ad-hoc,implementation
CNTWAYS - Editorial
PROBLEM LINKS
DIFFICULTY
EASY-MEDIUM
PREREQUISITES
Combinatorics, Modular Multiplicative Inverse
PROBLEM
There is a rectangle of N × M units. Another rectangle of A × B units is cut off from the upper right corner. Count the number of ways an ant can reach the bottom right corner starting from the top left corner, if it can only move right or down.
QUICK EXPLANATION
Split the path into 3 subpaths: (0, 0) -> (p, B-1) -> (p, B) -> (N, M). The answer is the sum of (number of ways to go from (0, 0) to (p, B-1)) × (number of ways to go from (p, B) to (N, M)) over all possible values of p.
EXPLANATION
A = B = 0
First, let's consider a simpler version of the problem where A = B = 0, i.e. the rectangle is intact. This becomes a traditional problem. To reach the bottom right corner, the ant needs to move right N times and move down M times. The order of moves does not matter. In other words, the ant needs to move N+M times, N of which the ant moves right. The number of ways, by combinatorics, is:
(N+M) choose N = C(N+M, N) = (N+M)! / (N! × M!)
Note that (N+M) choose N = (N+M) choose M.
Calculating C(N+M, N)
Since we have to calculate the answer modulo MOD = 1,000,000,007, the above formula have to be rewritten to
C(N+M, M) = ((N+M)! × N!-1× M!-1) mod MOD
Here, x-1 is the modular multiplicative inverse of x modulo MOD. Since MOD is a prime number, we can calculate it using Fermat's little theorem: x-1 = xMOD-2 (mod MOD). We can calculate xMOD-2 in O(lg MOD) time using exponentiation by squaring. Because we will use factorials many times in this solution, we can precompute all factorials and their inverses (modulo MOD) for all integers from 0 through 800,000, inclusive.
fact[0] = ifact[0] = 1 for i = 1; i ≤ 800000; i++: fact[i] = (i × fact[i-1]) mod MOD ifact[i] = (fact[i]MOD-2) mod MOD
Therefore the function C(X, Y) can be calculated in constant time as follows. For convenience, we also introduce function ways(N, M) that returns the number of ways an ant can reach the bottom right corner of an N × M intact rectangle.
function C(X, Y): return (fact[X] × ifact[X-Y] × ifact[Y]) mod MOD function ways(N, M): return C(N+M, M)
A, B > 0
Consider this ASCII art picture of a typical input rectangle. Assume that the top left corner is (0, 0) and the bottom right corner is (N, M).
+---------+ | | | | B | | A M + +-------------+ | | | | | | +-----------------------+ N
We can split the ant's journey from the top left corner to the bottom right in 3 phases:
Phase 1. The ant moves from top left corner to point (p, B-1):
+---------+ |\ | | \ | B | p | A M + +-------------+ | | | | | | +-----------------------+ N
Phase 2. The ant moves down from point (p, B-1) to point (p, B):
+---------+ |\ | | \ | B | p | A M + | +-------------+ | | | | | | +-----------------------+ N
Phase 3. Finally, the ant moves from point (p, B) to point (N, M):
+---------+ |\ | | \ | B | p | A M + | +-------------+ | \ | | ------------------\ | | \| +-----------------------+ N
Note that the phases are actually subproblems of the simpler problem mentioned before. The number of ways to perform Phase 1 is ways(p, B-1). The number of ways to perform Phase 2 is of course 1. Finally, the number of ways to perform Phase 3 is ways(N-p, M-B). Therefore, the number of ways if the ant passes point (p, B-1) and then point (p, B) is:
ways(p, B-1) × ways(N-p, M-B)
It is important to note that we do need an intermediate Phase 2 so that we do not count a path more than once.
To obtain the final answer, iterate over all possible values of p and sum the results. Here is a pseudocode of this solution.
read(N, M, A, B) res = 0 for p = 0; p ≤ N-A; p++: res += ways(p, B-1) × ways(N-p, M-B) println(res)
SETTER'S SOLUTION
Will be provided soon.
TESTER'S SOLUTION
Can be found here.
pointers and arrays c++
I have a project to dynamically create an array and do some actions into it namely:
- Function to create the dynamic array based on user input.
- Function to store elements in the array based on user input.
- Function to prints the elements in the array based on user input.
Function to delete the dynamic array.
and here's the part of my code to action #1:int menu(int choice) { displayMenu(); cin >> choice; cout << "\n"; if(choice == 1) { cout << "Enter size of the array: "; cin >> sizes; if(sizes > 0) { arr = new int[sizes]; cout << "\nArray has been created."; } cout << "\n\n"; menu(choice); }
And now my problem is that, when I do action 1, it creates the array, then IF i do action 3(show output) it output random numbers but the output must be a prompt ("array is empty") because I have to store elements first using action 2 to manually input the elements of the array. The creation of the array has random numbers in it. How can i get rid of that?
ANURRZ - How can an O(n^2) algorithm work?
The editorial suggests an algorithm which is of O(n^2). But there are at most 100 test cases too. So how can an O(n^2) algorithm work?
n^2 = 10^6
And there are 100 test cases, so 10^8 computations.
I am a beginner, and I've heard that we can not process more than 10^7 computations on codechef.
QSET - Editorial
PROBLEM LINK:
Author:Lalit Kundu
Tester:Shiplu Hawlader
Editorialist:Lalit Kundu
DIFFICULTY:
MEDIUM
PRE-REQUISITES:
Segment Trees, Number Theory
PROBLEM:
Given a string of digits of length N<(105), do two kind of operations(total of M<(105):
- Type 1: 1 X Y: Replace AX by Y.
- Type 2: 2 C D: Print the number of sub-strings divisible by 3 of the string denoted by AC, AC+1 ... AD.
Formally, you have to print the number of pairs (i,j) such that the string Ai, Ai+1 ... Aj, (C ≤ i ≤ j ≤ D), when considered as a decimal number, is divisible by 3.
QUICK EXPLANATION:
Use segment trees. Store in node for each interval,
- the answer for that interval
- count1[], where count1[i] denotes number of prefixes of interval which modulo 3 give i.
- count2[], where count2[i] denotes number of suffixes of interval which modulo 3 give i.
- total, sum of interval modulo 3.
Perform merge operations in constant time.
EXPLANATION:
We basically need to find number of subarrays in range L to R who sum is divisible by 3.
Queries are for ranges, where we have to count subarrays, we can use segment tree because we can solve our problem if we can merge two intervals and find answer for the new interval in constant time.
We can use segment tree because we can take two different subarrays and merge them in constant time to find answer for the new large subarray.
In segment tree, each subarray's information is recursively calculated from two smaller subarrays.
While querying, we can merge different(and disjoint) subarrays to get answer for range L to R.
So, we need to design the node of our segment tree. We store in our node, the answer for current subarray. Also, we will store two arrays count1[] and count2[] as defined above.
While merging two intervals(say node1 and node2), our new answer will be node1.answer + node2.answer, plus count of valid subarrays which start in node1 and end in node2.
This pseudo code will clear the things.
//merges node1 and node2 and stores in node3
merge(node1, node2, node3)
//non intersecting subarrays of node1 and node2
node3.ans = node1.ans + node2.ans
for i = 0 to 2:
for j = 0 to 2:
//if adding suffix of node1 with modulo i
//to prefix of node2 with modulo j
//gives us a subarray divisible by 3
if (i + j) % 3 == 0:
//all pairs of valid indexes are valid subarrays
node3.ans += node1.count2[i] * node2.count1[j]
Note now, we also need to build both array count1 and count2 for the new interval.
Let's build count1 first:
Say there were count1[i] prefixes of node2 which when taken modulo with 3 gave i. Now, all such prefixes will give (i + node1.total) % 3, where node1.total denotes total sum of interval modulo 3. So, we can calculate new arrays. In similar way, we can calculate count2.
//building count1 and count2
for i=0 to 2:
node3.count1[i] = node1.count1[i] + node2.count1[3-node1.total+i]
node3.count2[i] = node2.count2[i] + node1.count2[3-node2.total+i]
So, complexity is: O(N log N) preprocessing and O(log N) per query.
ALTERNATIVE SOLUTION:
Suppose we keep in segment tree for each node, how many prefix sums in this interval are divisible by 0,1,2.
For a query [L,R], we just have to count number of prefix sums in interval [L,R] divisible by 0,1,2(let's call them s1,s2,s3).
Our answer will be choose(s1,2)+choose(s2,2)+choose(s3,2).
Why? Because, suppose prefix_sum[i] % 3 = prefix_sum[j] % 3, then sum of substring [i+1, j] is divisible by 3.
For update query(mark A[x] = y), since we are keeping prefix sum modulo 3, for range [x, N], we increase/decrease each prefix sum by k(k<3). We can do this using lazy propagation.
SOLUTIONS:
AMR14C -Editorial
PROBLEM LINK:
DIFFICULTY:
EASY.
PREREQUISITES:
Hashing
PROBLEM:
Given an array, find out pair of numbers such their sum modulo M is less than or equal to X.
QUICK EXPLANATION:
As the naive solution will have time complexity of O(n2) which will not pass, So we can make a count array A, where A[p] = count of numbers whose value modulo M is p and we can check if first number module M is p, then in how many ways we can select another number. The time complexity of above solution will be O(M+N).
EXPLANATION:
Array A contains economy rates of the bowlers.
The naive solution will look like:
long long int answer = 0;
for(int i =0 ; i < N ; i++)
for(int j = 0 ; i< N ; j++)
if( (A[i] + A[j] <= x)
answer++;
cout<<answer<<endl;
But the given solution has time complexity O(n2) which will not pass in the given time limit.
As you can notice that, the value of M is not large and a solution having time complexity of O(M) will pass.
An O(M2) approach:
Make an array B. where
B[k] = count of numbers in array A which has value of k on taking modulo M.
Now another naive approach can be written in following manenr having time-complexity of O(M2).
long long int answer = 0;
for(int i = 0 ; i< M ; i++)
for(int j = 0 ; j< M ; j++)
if( (i+j)%M <= x)
answer += B[i]*B[j];
cout<<answer<<endl;
In this approach, we are taking all such number, whole modulo M value i or j and if their sum modulo M is less than or equal to x, then they will contribute to the answer.
The above solution will also not pass, as time complexity of given solution is O(M2).
Now we will try to optimize the solution to O(M).
as we can observe that if we want ((i+j)%M) <=x, and we have fix the value of i. then j can take only few contiguous values.
There will be two cases.
So, for the case I where i<=x:
for(int i=0 ; i<= x; i++)
answer += B[i]*(B[0] + B[1] + ....+ B[x-i])
As we can see that the values which we are multiplying will B[i], their indices are contiguous in nature, so we can use the idea of prefix sum to get the value of the range sum in O(1) time.
Define Pre[i] = B[0] + B[1] + ... + B[i] then B[i] + .... + B[x-i] = Pre[x-i] - Pre[i-1]
So modified code will look like :
for(int i=0 ; i<= x; i++)
answer += B[i]*(Pre[x-i] - Pre[i-1]);
Similarly we can handle the second case when i>=x . Time complexity of the above solution will be O(M+N), which will easily pass in given time limit.
Editorialist's Solution:
Editorialist's solution can be found here.
XRQRS RUNTIME ERROR (SIGSEGV)
play with strings
I'm getting a runtime error. But when I compile it with custom input it works.
import java.io.*;
class play
{
int l1,l2;
String s1,s2;
char A[]=new char[100];
char B[]=new char[100];
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void main()throws IOException
{
int t;
t=Integer.parseInt(br.readLine());
while(t-->0)
{
s1=br.readLine();
s2=br.readLine();
s1=s1.toLowerCase();
s2=s2.toLowerCase();
arr();
check();
}
}
void arr()
{
l1=s1.length();
l2=s2.length();
for(int i=0;i<l1;i++) {="" a[i]="s1.charAt(i);" }="" for(int="" i="0;i<l2;i++)" {="" b[i]="s2.charAt(i);" }="" }="" void="" check()="" {="" int="" j="0,count=0,c2=0;" for(int="" i="0;i<l1;i++)" {="" if(a[i]="=B[j])" {="" count++;="" j++;="" }="" }="" j="0;" for(int="" i="(l1-1);i">=0;i--)
{
if(A[i]==B[j])
{
c2++;
j++;
}
}
if((count==l2)&&(c2!=l2))
{
System.out.println(1);
}
else
if((count!=l2)&&(c2==l2))
{
System.out.println(2);
}
else
if((count==l2)&&(c2==l2))
{
System.out.println("3");
}
else
System.out.println("0");
}
public static void main(String args[])throws IOException
{
play ob=new play();
ob.main();
}
}
How to Approach Mathematically And Logically for this Question (Age Of Exploration)
Initially you are provided with some People And Resources(Own/Capacity)
Settlers(10/100)
Trees(0/5K)
Wood(2.5K/5K)
Stones(3K/5K)
Work your way through each of the below resources, and calculate the final fastest time for the best case of production.
Also attatch/provide your approach of solution.
Starting time is 00:00:00:00 (day:hr:min:sec)
Consider all buildings to be ideal, i.e. they themselves take no time to build.
Tree Feller
Cost : 1 Settler, 100 Stones, 200 Wood
Production : Trees(10/min)
Stone Cutter
Cost : 1 Settler, 320 Stones, 240 Wood
Production : Stones(10/min)
Sawmill
Cost : 1 Settler, 200 Stones, 300 Wood
Consumption : Trees(20/min)
Production : Wood(20/min)
Small House
Cost : 400 Stones, 300 Wood
Production : +10/10 Settlers(0.001/min)
Small Storage
Cost : 2.5K Stones, 2.5K Wood
Production : +0/5K Resources
Fisherman
Cost : 1 Settler, 150 Stones, 200 Wood
Production : Fish(10/min)
Hunter
Cost : 1 Settler, 250 Stones, 400 Wood
Production : Meat(2/min)
Small Food Storage
Cost : 1 Settler, 800 Stones, 1.2K Wood
Consumption : Fish(5/min), Meat(2/min)
Production : Food(5/min)
Medium Storage
Cost : 10K Stones, 10K Wood
Production : +0/20K Resources
Big Storage
Cost : 50K Stones, 50K Wood
Production : +0/100K Resources
Medium House
Cost : 1.6K Stones, 1.2K Wood
Consumption : Food(5/min)
Production : +20/30 Settlers(0.01/min)
Farm
Cost : 1 Settler, 1K Stones, 1.4K Wood
Production : Corn(20/min)
Mill
Cost : 1 Settler, 1.6K Stones, 2.5K Wood
Consumption : Corn(10/min)
Production : Flour(10/min)
Water Well
Cost : 1 Settler, 1.5K Stones, 1K Wood
Production : Water(20/min)
Bakery
Cost : 1 Settler, 2K Stones, 2.8K Wood
Consumption : Flour(10/min), Water(10/min)
Production : Bread(10/min)
Medium Food Storage
Cost : 1 Settler, 6K Stones, 4.8K Wood
Consumption : Fish(5/min), Bread(5/min)
Production : Food(20/min)
Piggery
Cost : 1 Settler, 4.5K Stones, 7K Wood
Consumption : Corn(10/min), Water(10/min)
Production : Meat(20/min)
Big Food Storage
Cost : 1 Settler, 12K Stones, 10K Wood
Consumption : Meat(20/min), Bread(5/min)
Production : Food(100/min)
Big House
Cost : 6K Stones, 4.5K Wood
Consumption : Food(20/min)
Production : +30/50 Settlers(0.1/min)
Iron Mine
Cost : 1 Settler, 10K Stones, 12K Wood
Production : Iron Ore(5/min)
Coal Mine
Cost : 1 Settler, 14K Stones, 16K Wood
Production : Coal(10/min)
Iron Melt
Cost : 1 Settler, 24K Stones, 18K Wood
Consumption : Iron Ore(5), Coal(5/min)
Production : Iron(1/min)
Weapon Forge
Cost : 1 Settler, 26K Stones, 22K Wood
Consumption : Iron(1/min), Coal(5/min)
Production : Swords(0.2/min)
Barrack
Cost : 12K Stones, 15K Wood
Consumption : Settler(0.2/min), Swords(0.2/min)
Production : Soldiers(0.2/min)
Watch Tower
Cost : 10 Soldiers, 24K Stones, 14K Wood
Production : +0/100 Soldiers
Gold Mine
Cost : 16 Settlers, 16K Stones, 20K Wood
Production : Gold Ore(5/min)
Gold Melt
Cost : 1 Settler, 32K Stones, 28K Wood
Consumption : Gold Ore(5/min), Coal(5/min)
Production : Gold(1/min)
Mint
Cost : 1 Settler, 48K Stones, 36K Wood
Consumption : Gold(1/min), Coal(5/min)
Production : Gold Coins(15/min)
Castle
Cost : 50 Soldiers, 80K Stones, 120K Wood, 500 Gold Coins
Production : +0/1K Soldiers
Shipyard
Cost : 1 Settler, 90K Stones, 130K Wood
Consumption : Gold Coins(5/min), Wood(20/min)
Production : +0/10 Ships(0.01/min)
Expendition
Cost : 100 Soldiers, 100 Settlers, 1 Ship, 1K Food, 1K Gold Coins
Production : +1 Foreign Country
Crusade
Cost : 500 Soldiers, 1 Foreign Country, 5 Ships, 5K Food, 10K Gold Coins
Production : +1 Colonies
Banana Plantation
Cost : 1 Colonies, 100 Settlers, 120K Stones, 150K Wood
Production : Bananas(100/min)
Banana Ship
Cost : 1 Ship, 50 Settlers, 1K Gold Coins
Consumption : Bananas(100/min)
Production : Gold Coins(50/min)
Coffee Plantation
Cost : 1 Colonies, 250 Settlers, 180K Stones, 210K Wood
Production : Coffee(1K/min)
Coffee Ship
Cost : 1 Ship, 50 Settlers, 1K Gold Coins
Consumption : Coffee(1K/min)
Production : Gold Coins(100/min)
Cotton Plantation
Cost : 1 Colonies, 350 Settlers, 260K Stones, 300K Wood
Production : Cotton(100/min)
Cotton Ship
Cost : 1 Ship, 50 Settlers, 1K Gold Coins
Consumption : Cotton(100/min)
Production : Gold Coins(250/min)
Arc De Tromphe
Cost : 600K Stones, 800K Wood, 500K Gold Coins
Bin Ben
Cost : 1M Stones, 780K Wood, 750K Gold Coins
Ayers Rock
Cost : 2.5M Stones, 1M Gold Coins
Niagra Falls
Cost : 4M Stones, 5M Wood, 3M Gold Coins, 1M Water
Grand Canyon
Cost : 9.9M Stones, 9.9M Wood, 9.9M Gold Coins
How do I approach this ?
There is a function getWord() which takes word as input and checks whether word is present in the dictionary.Given a long word as input find all the meaning full ( i.e getWord() is true ) that can be made from the given input . Example : Input : antin output : a , an , ant, tin, in.
I am not able to find any solution other than brute force .....If you have one, please do share..It will be a great help.Please do mention the type of the problem also, so that I can start studying those type and their approach.......THANKS A LOT
Sorting an array containing three elements only
Give an array of length 10^7 but having only three elements R,G,B ....What is the best approach to sort it in least time and space complexity.... one of the methods is memory map........I got to know that this question has multiple solutions
Data Structures and Algorithms
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.
Binary Search : Tutorial, Problems, Tutorial, Implementation, Problem
Quicksort : Tutorial, Implementation, Tutorial
Merge Sort : Tutorial, Implementation, Tutorial
Suffix Array : Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem
Knuth-Morris-Pratt Algorithm (KMP) : Tutorial, Tutorial, Implementation, Tutorial, Problem
Rabin-Karp Algorithm : Tutorial, Implementation, Tutorial, Problem, Problem
Tries : Tutorial, Problems, Tutorial : I,II, Tutorial, Problem, Problem, Problem
Depth First Traversal of a graph : Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem
Breadth First Traversal of a graph : Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem, Flood Fill
Dijkstra's Algorithm : Tutorial, Problems, Problem, Tutorial(greedy), Tutorial (with heap), Implementation, Problem, Problem
Binary Indexed Tree : Tutorial, Problems, Tutorial, Original Paper, Tutorial, Tutorial, Problem, Problem, Problem, Problem, Problem, Problem, Problem
Segment Tree (with lazy propagation) : Tutorial, Implementation, Tutorial, Tutorial, Problems, Implementation, Tutorial, Implementation and Various Uses, Persistent Segment Tree, problems same as BIT, Problem, Problem/HLD is used as well/
Z algorithm : Tutorial, Problem, Tutorial, problems same as KMP.
Floyd Warshall Algorithm : Tutorial, Implementation, Problem, Problem
Sparse Table(RMQ) : Tutorial, Problems, Tutorial, Implementation(C++), Java implementation
Heap / Priority Queue / Heapsort : Implementation, Explanation, Tutorial, Implementation, Problem, Chapter from CLRS
Suffix Automaton : Detailed Paper, Tutorial, Implementation (I), Tutorial, Implementation (II), Problem, Problem, Problem, Problem, Tutorial, Implementation
Lowest Common Ancestor : Tutorial, Problems, Paper, Paper, Problem, Problem, Problem
Counting Inversions : Divide and Conquer, Segment Tree, Fenwick Tree, Problem
Suffix Tree : Tutorial, Tutorial, Intro, Construction : I, II, Implementation, Implementation, Problem, Problem, Problem, Problem
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
Basic Data Structures : Tutorial, Stack Implementation, Queue Implementation, Tutorial, Linked List Implementation
Graphs : Definition, Representation, Definition, Representation, Problem, Problem
Minimum Spanning Tree : Tutorial, Tutorial, Kruskal's Implementation, Prim's Implementation, Problem, Problem, Problem, Problem, Problem
Combinatorics : Tutorial, Problems, Problem, Tutorial
Union Find/Disjoint Set : Tutorial, Tutorial, Problems, Problem, Problem, Problem
Knapsack problem : Solution, Implementation
Aho-Corasick String Matching Algorithm : Tutorial, Implementation, Problem, Problem, Problem, Problem
Strongly Connected Components : Tutorial, Implementation, Tutorial, Problem, Problem, Problem
Bellman Ford algorithm : Tutorial, Implementation, Tutorial, Implementation, Problem, Problem
Heavy-light Decomposition : Tutorial, Problems, Tutorial, Implementation, Tutorial, Implementation, Implementation, Problem, Problem, Problem
Convex Hull : Tutorial, Jarvis Algorithm Implementation, Tutorial with Graham scan, Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem
Line Intersection : Tutorial, Implementation, Tutorial, Problems
Interval Tree : Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem, Problem, Tutorial
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
K-d tree : Tutorial, Tutorial, Implementation, Problem
Binary Search Tree : Tutorial, Implementation, Searching and Insertion, Deletion
Quick Select : Implementation, Implementation
Treap/Cartesian Tree : Tutorial(detailed), Tutorial, Implementation, Uses and Problems, Problem, Problem
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
STL (C++) : I,II, Crash Course
Manacher's Algorithm : Implementation, Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem, Problem
Detecting Cycles in a Graph : Directed - I, II Undirected : I
Backtracking : N queens problem, Tug of War, Sudoku
Eulerian and Hamiltonian Paths : Tutorial, Tutorial, (Eulerian Path and Cycle)Implementation, (Hamiltonian Cycle)Implementation
Graph Coloring : Tutorial, Implementation
Meet in the Middle : Tutorial, Implementation
Johnson's Algorithm : Tutorial, Tutorial, Implementation
Maximal Matching in a General Graph : Blossom/Edmond's Algorithm, Implementation, Tutte Matrix, Problem
Recursion : I,II, Towers of Hanoi with explanation
Link-Cut Tree : Tutorial, Wiki, Tutorial, Implementation, Problem, Problem, Problem, Problem
Euler's Totient Function : Explanation, Implementation, Problems, Explanation, Problems
Edit/Levenshtein Distance : Tutorial, Introduction, Tutorial, Problem, Problem
TLE using sets
LCH15JGH - Editorial
PROBLEM LINK:
Author:Pavel Sheftelevich
Tester:Roman Rubanenko
Editorialist:Paweł Kacprzak
DIFFICULTY:
Medium Hard
PREREQUISITES:
Math, [Fenwick tree][11111], Segment tree, Ad-hoc
PROBLEM:
There are initially N families of people of a different given size. You have to be able to handle 3 types of queries on the set of these families:
- Add one family of size X to the set
- Remove one family of size X from the set
- You will give Y bananas to every family in the set in such a way that for any particular family, all member of it will receive the same number of bananas and this number will be maximum possible i.e if a family has M members then every member will receive Y / M bananas and there will be Y % M bananas left. Your tast is to count the number of all bananas left in this process.
QUICK EXPLANATION:
Use the fact that x % y = x - (x / y) * y, where x / y is an integer division, so in order to calculate the number of bananas left you can avoid calculating modulo. To handle queries of the first and the second type you can use a [Fenwick tree][11111] or a Segment tree, which can answer two queries: how many total people are currently in families for which Y / M is equal and how many families are there for which Y / M is equal, where M denotes the number of people in one such family. If you are able to answer this question, in order to answer a query of the third type, you can iterate over all possible values of Y / M and accumulate the results.
EXPLANATION:
There are multiple very good approaches for this problem and almost all of them depends on the facts given above. I will sketch 3 of them:
SOLUTIONS BASED ON SEGMENT-TYPE-LIKE DATA STRUCTURE
As mentioned in quick explanation, you can use a data structure which can handle queries about segments, where a segment [L, R] corrensponds to all families with sizes in a range [L, R]. If you are able to keep track of these ranges, you can easily handle queries of first two types. In order to handle the third query, notice that there are many families of different sizes for which Y / M is equal, where M denotes a size of a family. Based on this fact, and the fact that Y % M = Y - (Y / M) * M, you can avoid calculating modulo on every such family and you can calculate a result for all such familis at once by querying the data structure about the number of people in families in a range [L, R] in which Y / M is equal for every family and querying it also about the number of families in the same range. Based on this two subresults, you can compute the number of bananas left in the process for each of family in [L, R]. If you sum these results over all possible values of Y / M you will get the result for the third query.
The complexity of these solutions are about O(log N * M * sqrt(max(Y)))
SOLUTIONS BASED ON BLOCKS
Rather than using a segment-based data structure, you can divide the range of possible family sizes in contant size blocks. You can use similar facts as in the above solution to get the results, but rather than querying for a particular range [L, R] you will divide it into two calculations of result for a range [1, L - 1] and [1, R] and you will subtract first from the second. In order to calculate the result for a given range [1, R] you will sum results for all full blocks which fit into the range and possibly one chunk at the end of the range for which you can calculate the result iterating over all its elements.
Let B be the number of used blocks and S be the size of one such block.
The complexity of these type solutions are about O(M * sqrt(max(Y)) + N * (B + S)) which can be an upgrade over the segment-tree-like data structure.
AD HOC SOLUTIONS
You can also keep it really simple and get away with using advanced data structures or blocks. A quick overview is that you can compute the results for families given initially in some way, then handle a portion of up to Q queries (Q is choosen arbitrary to fit the time limits, we saw contestants using Q = 200) by using previously computed results and bruteforcing over previous updates in current portion of queries. After you handle Q queries, you can rebuilt your current results and start with another Q queries.
The complexity of these type solutions depends on the implementation, but if done right with appropriate constants, they can be really fast for this problem.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here. Tester's solution can be found here.
RELATED PROBLEMS:
Recursion Challenge
Can anyone please tell me why tle on http://www.codechef.com/viewsolution/6003932 . And a person has very fast program with http://www.codechef.com/viewsolution/6001493
LCH15JEF - Editorial
PROBLEM LINK:
Author:Pavel Sheftelevich
Tester:Roman Rubanenko
Editorialist:Paweł Kacprzak
DIFFICULTY:
Easy
PREREQUISITES:
Math, Big-num
PROBLEM:
For each test case you are given a number m and an expression which contains only numbers multiplications and exponentiations. Your task is to find the value of the expression modulo m
QUICK EXPLANATION:
Parse the expression and calculate it using big num representation and fast exponentiation.
EXPLANATION:
EXPECTED SOLUTION:
If we are able to handle 3 operations: multiplication, exponentiation and modulo calculation, we can solve the problem easily after parsing the input first. Since input numbers can be very large, this is not straightforward and I'll show how to implement these 3 operations step by step:
Calculating modulo. Let assume that we have to calculate A % M. In this problem M is always < 10^8 so we can store it as 64-bit integer. Let dk-1, dk-2, ..., d0 be the digits of A from left to right. Then A = 10^(k-1) * dk-1 + 10^(k-2) * dk-2 + ... + d0 and based on this fact, we can write A % M as (10^(k-1) * dk-1) % M + (10^(k-2) * dk-2) % M + ... + d0 % M which can be easily computed using Horner's method - please check the author's solution for details.
Exponentiation. Let assume that we have to calculate A^B, where A and B can be arbitrary long numbers. First we can calculate reduce A to A^M because (A^B) % M = ((A%M)^B) % M. So now we are raising a number A < 10^8 to an arbitrary long exponent. Let B = 10^(k-1) * dk-1 + 10^(k-2) * dk-2 + ... + d0 where di is the i-th rightmost digit of B. Then A^B = A^(10^(k-1) * dk-1 + 10^(k-2) * dk-2 + ... + d0) which can be written as A^(10^(k-1) * dk-1) * A^(10^(k-2) * dk-2) * ... * A^d0 and you can again use the Horner's method to compute it - please check the author's solution for details.
Multiplication of two numbers A, B < 10^18 modulo MOD < 10^18. The result of this operation may not fit into 64-bit integer, so we have to be smart here. You can use the same idea as in the fast exponentiation algorithm here, please check this function from author's code:
long long MOD; long long mult(long long A, long long B) { if ( B == 0 ) return 0; long long u = mult(A, B/2); long long res; if ( B%2 == 0 ) res = u + u; else res = u + u + A; while ( res >= MOD ) res -= MOD; return res; }
SOLUTION USING BIG NUMS:
Since numbers in the statement can be very large and m can be big also, this problem is very easier to code in a language which has implemented a big number representation. For example Java or Python is a really good choice here. If you are planing to write the solution in a language which doesn't support big numbers, you have to implement it on your own along with operation of multiplication, fast exponentiation (which is done by multiplication) and modulo calculation. The bottom line is that you have a strong advantage here if you are using a language which supports big numbers or you have an implementation of it prepared before the contest.
I will focus now on the implementation, because if you do it fast and smart, you can benefit huge from it.
First things first, we have to parse the input statement, because it is given as a string of numbers and operands. If you are familiar with regular expressions, you are in a pole position here. Let change two start representing exponentiation to ^ symbol duo to formatting issues in this editor only for editorial purposes. If we divide the statement x1^y1 * x2^y 2 * ... * xn^yn into pairs of numbers (x1, y1), (x2, y2), ..., (xn, yn) we can first compute the result of exponentiation for each pair and then multiply these intermediate results. So let's split the input statement just into consecutive numbers! Then we can get two such numbers, do the exponentiation on them and multiply the current result by the result of this exponentiation - remember that all operations have to be calculated modulo m.
If you are using python or another language with regular expressions built in, you can split the input statement s in consecutive numbers using the below regular expression:
re.split(r'[^0-9]+', s)
where s is the input string and re is the standard regular expression module
In python there is a built in fast exponentiation functions which can also calculate the result modulo given number. To compute (a^b) % c just run mod(a, b, c). I encourage you to use it, because it is really fast and very well implemented.
If you want to know how to do fast exponentiation on your own, please check this link. One important note is that for big exponents, a resursive exponentiation of it will give you Runtime Error duo to stack overflow. You should implement it iteratively.
Since my python solution in quite short, you can see the full code below:
import re t = int(raw_input()) for i in xrange(t): m, s = raw_input().strip().split() m = long(m) s = s.strip() a = re.split(r'[^0-9]+', s) res = 1 for i in xrange(0, len(a), 2): res = (res * pow(long(a[i]), long(a[i + 1]), m)) % m print res
ALTERNATIVE SOLUTIONS:
For the first subtask, you don't have to use big numbers at all since numbers in the expression are digits and m is small enough. For the second subtask, every result of an exponentiation can be keeped small when calculated modulo m, because m < 10^9 and this allows you to do multiplication in the statement in 64-bit integers because a * b, for a, b < 10^9 fits 64-bit integer.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
RELATED PROBLEMS:
Maximizing Minimum possible distance between number of points
I have come across some problem. I have been given N points , from which I have to select K points. Each points is having some distance from the origin. say there are 5 points with distance from origin 10, 15,20,25,30. I have to select three of them so that minimum distance between them is maximized. So here I will select 10, 20, 30. What can be the possible approach to this problem?
Wrong Answer in Cricket Tournament : RECCKT (RECursion Challenge-I)
I was doing a problem in Recursion Challenge - I. (problem link), and I comes up with an algorithm, but its not accepting my solution. Can someone please tell me where is the flaw.
Problem Description: You are given an array A of size N. You have to find the maximum fluctuation in the array.
Fluctuation = max (A[j]-A[i]) for all i,j satisfying 1 ≤ i < j ≤ N.
NOTE: fluctuation can be negative.
Constraints: 2 ≤ N ≤ 1000, 0 ≤ A[i] ≤ 10^9
My Algorithm (considering 1-based indexing)
function solve (N):
max_difference = a[2]-a[1]
smallest = a[1]
for index in 2 to N:
max_difference = max(max_difference, a[index]-smallest)
if (max_difference < a[index]-a[index-1])
max_difference = a[index]-a[index-1]
smallest = a[index-1]
return max_difference
Please help guys.
Dont know how to approach these type of questions(pure logic based)
hello @all ,this is not purely programming related question but it is related somehow..i am weak in maths and i face difficulty on attempting the question which involve some crazy mathematics like this i know there is some maths or some repetitive pattern behind the scenes but i usually don't get what it is.Any suggestion from you guys because my aim is not to get good rating but to do 700+ question till dec'15..and there are many question of these kind.So this is the hurdle.Should i read some reasoning books or anything else.please guys do comment.
prime factorization
We are given two integers I and j.we have to print x (I<=x<=j) such that number of divisors of x is maximum.if there are more than 1 x possible then print lowest x and also its number of divisors.
Constraint::
1<=I<=j<=10^9
j-I<=10000 e.g.
Input:
1 10
Output: 6 has 4 factors.
My approach:
1) segmented sieve upto 10^9.
2) then brute force from I to j.
Is there any better method??
This is not my homework!!!!
One of the regional question from ACM ICPC
Is there any better method??