include <iostream>
using namespace std; int main() { int A,B,p,q,dif; cin>>A >>B; dif=A-B; p=dif/10; if((dif%10)==9) q=(dif%10)-1; else q=(dif%10)+1; cout<<"\n"<<p<<q; return 0; }
using namespace std; int main() { int A,B,p,q,dif; cin>>A >>B; dif=A-B; p=dif/10; if((dif%10)==9) q=(dif%10)-1; else q=(dif%10)+1; cout<<"\n"<<p<<q; return 0; }
www.hackerrank.com/june-contest we are organising a contest of 2 and half hours on 15th june at 9:00 pm ist to 11:30 pm ist on hackerrank.
link for author soln is https://s3.amazonaws.com/codechef_shared/download/Solutions/JUNE18/setter/SHKSTR.cpp
Author:Avijit Agarwal
Tester and Editorialist:Soumik Sarkar
CAKEWALK
Strings, Sorting
Given a string $S$ find the frequency of each character in the string and check whether they can be rearranged into a sequence $F$ where $F_i = F_{i-2} + F_{i-1}$ holds for all $i \ge 3$.
Finding the frequency of each character can be done in linear time. One possible way is below
m = empty map
for each character c in S:
if c in m:
m[c] = m[c] + 1
else:
m[c] = 0
F = empty list
for each key, value in m:
append value to F
Next we can say that because $F_i = F_{i-1} + F_{i-2}$ and $F_{i-2}$ cannot be $0$, $F_i > F_{i-1}$ for all $i \ge 3$. So it makes sense to sort the array $F$.
Then we can check if $F$ satisfies the given condition for all $i \ge 3$. If it does, then the string is dynamic otherwise it is not, right? ......But hold on, there is a catch. Indeed $F_i > F_{i-1}$ for all $i \ge 3$, but what about $F_2$? The relation between $F_2$ and $F_1$ is not specified. So it maybe that $F_4 \ne F_2 + F_3$ in the sorted order but $F_4 = F_1 + F_3$. In that case if we can simply swap $F_1$ and $F_2$ to get the required sequence and the string is dynamic.
For example: $F = (1, 2, 3, 4)$. Here $3 = 1 + 2$ but of course $4 \ne 2 + 3$. If we swap $1$ and $2$ we will get $(2, 1, 3, 4)$ where $3 = 2 + 1$ and $4 = 1 + 3$.
sort F
N = length of F
if N >= 4 and F[4] != F[2] + F[3]:
swap(F[1], F[2])
ok = True
if N >= 3:
for i in [3..N]:
if F[i] != F[i - 1] + F[i - 2]:
ok = False
if ok:
S is dynamic
else:
S is not dynamic
Author's solution can be found here
Tester's solution can be found here.
Hey guys I have started a new blog. The first article is on dfs lowlinks . You can read it up here. Feel free to comment if anything is wrong or suggest any changes you want me to make. Also feel free to suggest topics you want me to write some article on . Thanks. :D
Author:Noszály Áron
Tester:Misha Chorniy
Editorialist:Bhuvnesh Jain
MEDIUM
Factroisation, Combinatorics
You are given $N$ workers and each of them has a deadline to complete the work, given by $d_i$ for $i^{th}$ worker. Each worker completes the work in $1$ day and on each day at most $1$ worker can work. You need to decide to the array containing the deadline for every worker such that the number of ways in which the workers can decide to work is $C$ and $d_n$ is minimised. Also, the array of deadlines should be sorted.
Before proceeding towards the solution, we need to find the number of ways in which workers can decide to work for a given array $d_1 ≤ d_2 ≤ \cdots ≤ d_n$.
Consider the case for $n ≤ 3$. Let $d_1 = x, d_2 = y, d_3 = z$. We have the following dynammic programming solution
$$dp[x] = x$$
$$dp[x][y] = dp[x] * (y - x) + dp[x-1] * x = xy - x^2 + x^2 - x$$
$$dp[x][y] = xy - x = (y-1) * dp[x]$$
$$dp[x][y][z] = dp[x][y] * (z - y) + dp[x][y-1] * (y - x) + dp[x-1][y-1] * x$$ $$dp[x][y][z] = (xy - x)(z - y) + (xy - 2x)(y - x) + (xy - 2x - y + 2)x$$ $$dp[x][y][z] = (xyz - xz - 2xy + 2x) = (z - 2) * (xy - x)$$ $$dp[x][y][z] = (z - 2) * dp[x][y]$$
Using the above observations, it is clear that number of ways is $\prod_{i=1}^{i=n} {(d_i - i + 1)}$. We can even prove it combinatorially. The first person has $d_1$ choices, the second one has $(d_2 - 1)$ choices and so on. By the principle of multiplication, the number of ways comes out to be same.
Note the above solution clearly points out that $d_i >= i$. Thus for $C = 1$, the array is $(1, 2, 3, 4, \cdots)$.
Thus, the problem now reduces to finding an array $d_1 ≤ d_2 ≤ \cdots ≤ d_n$ such that $\prod_{i=1}^{i=n} {(d_i - i + 1)} = C$ and $d_n$ is minimised.
Instead of finding $d_1, d_2 \cdots d_n$, we will find sorted array, $d_1, (d_2-1), \cdots, (d_n-n+1)$, such that product of this sequence is $C$ and later add back $(i - 1)$ to every term to ensure that sequence is increasing.
We can use dynamic programming based solution for this subtask. Let $dp[N][C]$ denote the minimised value of $d_n$ for which the sequence $d_1, d_2, \cdots, d_n$ has number of ways as $C$. The transitions are simple. Let $dp[N][C] = x$. So, we need to find the minimum value for the sequence with $(N - 1)$ terms and product as $(C/x)$. The possible candidates are the divisors of $(C/x)$. So, we try all possible candidates and update our answer whether or not it is possible to form an array with the tried candidate. Once, the dynamic programming table is built, we can simply backtrack it to print the answer.
The time compleixty of the above approach is $O(N * {\sigma_{0}{(C)}}^2)$, where $\sigma_{0}{(C)}$ denotes the number of divisors of $C$.
For details, you can refer to author's solution for the above approach.
We may see that for optimal answer, the sequence $d_1, (d_2-1), \cdots, (d_n-n+1)$, looks like the following for large $n$:
[zero or more numbers greater than 1] [bunch of ones] [zeros or more numbers greater than 1]
Outline of proof for above claim: Basically we want to show that if we have a solution that is not in the above form, then there's a solution of the above form which has the same last element. We achieve this by moving the blocks of non $1$ elements as a unit, in this part, we will use the monotonicity of array $d$ as an argument to show that the blocks are indeed movable and don't break anything.
The above form is important because increasing $N$ actually just pushes more ones into the middle (if there were a better way to distribute the numbers we would have used it earlier). So to solve, we calculate the optimal sequence for smaller $N$ and then extend the "bunch of ones" in the middle.
In the worst case the above method's complexity is $O(N + (\text{number of prime factors of C}) * {\sigma_{0}{(C)}}^2)$. Because the number of prime factors in the range of ${10}^9$ is $30$ in the worst case and the number of divisors is $1000$ in the worst case, this gives around $3 * {10}^7$ operations per test case.
For more details, you can refer to the setter's or tester's solution below.
We will first store all the factors of $C$. Now, we traverse the factors one by one and check if we can form an array $d_1, (d_2-1), \cdots, (d_n-n+1)$, such that the last element is given factor. Is yes, we simply update the answer. Below is the pseudo-code for checking whether we can find an array with the last element as given factor $x$.
# facts store the factors of C.
# facts[idx] = x
def check(idx):
ptr = n
prod = c
while ptr > 0:
while prod % facts[idx] != 0
idx -= 1
prod /= facts[idx]
ans[ptr] = facts[idx] + ptr - 1
ptr -= 1
if idx != len(facts)-1 and facts[idx] == (facts[idx+1] - 1):
idx += 1
if idx == 0 or prod == 1:
break
return (prod == 1)
Let us analyse the above pseudo-code. We first try to greedily find the first largest factor of the remaining product. At first step it will be $facts[idx] = x$, the number we want to check. Since in final array we want $d_{(i-1)} ≤ d_i$ and we are finding array $(d_i - i + 1)$, the previous term can now contain a possible larger factor only if it is greater than the previous factor by $1$. The last condition just checks that if the product has become 1, then we know the trivial answer or if the factor to be considered is $1$, the product will remain same. Below is an example iteration of the above for $N = 8$ and $C = 36$. Let the factor to be checked is $x = 2$.
$$\text{facts} = {1, 2, 3, 4, 6, 9, 12, 18, 36}$$
$$\text{Step 1} = {\cdots, 2}$$
$$\text{Step 2} = {\cdots, 3, 2}$$
$$\text{Step 3} = {\cdots, 3, 3, 2}$$
$$\text{Step 4} = {\cdots, 2, 3, 3, 2}$$
Since the prod now becomes $1$ we break. To build the required array we add the offsets $(i - 1)$ to the array.
Thus, required array is $(1, 2, 3, 4, 6, 8, 9, 9)$. Note that this may or may not be the optimal solution. It just shows how we check if a given factor can form the series if it is the last term in the sequence.
The time complexity of the above approach will be $O(\sigma_{0}{(C)} * \log{C} + N)$. This is because, for every factor, the checking will take $O(\log{C})$ step in the worst case as "prod" variable will decrease by a factor of atleast $2$ in each iteration. The second term, $O(N)$, is for building the complete sequence containing the initial trivial part of $(1, 2, 3, \cdots)$ and printing the answer. The space complexity will be $O(N + sqrt(C))$.
Once, you are clear with the above idea, you can see the editorialist implementation below for help.
Feel free to share your approach, if it was somewhat different.
$O(N + (\text{number of prime factors of C}) * {\sigma_{0}{(C)}}^2)$ or $O(\sigma_{0}{(C)} * \log{C} + N)$
$O(sqrt(C) + 1000 * sqrt(C) + N)$, where $1000$ denotes the value of small $N$ used by author to solve problem by dynamic programming.
Author's solution can be found here.
Tester's solution can be found here.
Editorialist's solution can be found here.
Hello CodeChef Community!
We’re happy to present to you another fresh set of challenges for your coding skills with the June Cook-Off 2018 sponsored by ShareChat. In addition, there are some exciting job/internship opportunities by ShareChat in the June Cook-Off 2018. More details on the June Cook-Off contest page here: COOK95 Looking forward to seeing your participation in yet another exciting monthly contest! Joining me this time on the problem setting panel are:
Time: 17th June 2018 (2130 hrs) to 18th June 2018 (0000 hrs). (Indian Standard Time — +5:30 GMT) — Check your timezone.
Contest link:https://www.codechef.com/COOK95
Registration: You just need to have a CodeChef handle to participate. For all those, who are interested and do not have a CodeChef handle, are requested to register in order to participate.
Prizes: Top 10 performers in Global and Indian category will get CodeChef laddus, with which the winners can claim cool CodeChef goodies. Know more here: https://discuss.codechef.com/questions/51999/how-do-i-win-a-codechef-goodie. (For those who have not yet got their previous winning, please send an email to winners@codechef.com)
Good Luck!
Hope to see you participating!
Happy Programming!
Can i get correct value of medium using this formula: 3median = 2mean + mode.
Or i have to explicitly figure out through element wise compare.
//also i have checked by breaking the whole program in different funtions.
void fun(); int i,j,k; char el;
int main()
{ int t;
scanf("%d",&t);// taking the number of inputs
el=getchar();//fflush is not working .. to absorb the /n of previous scanf ..else it's making
the program to malfunction
for(;t>0;t--)
fun(); //calling the fun to get the job done
return 0 ;
}
void fun()
{
int i=0,j=0,k=0;
int fre[24]={0}; // array to store the frequency of elements
int temp;
char ele[24]={0}; // array to store the elements
while(el=getchar())
{
if(!(el>=97&&el<=122))
break; //there may some problem in this condition
for(j=0;j<k;j++) //checking for match in the array
{
if(el==ele[j])// if match found then only incrementing the count
{
fre[j]+=1;
break;
}
}
if(j==k)// if match does not found then including the elemetn in ele[] and making corresponding count
{
ele[k]=el;
fre[k]=1;
k++;
}
}
for(i=0;i<(k-1);i++) // sorting the array of count to get applied the fib logic
{
for(j=(i+1);j<k;j++)
{
if(fre[i]<fre[j])
{
temp=fre[i];
fre[i]=fre[j];
fre[j]=temp;
}
}
}
if(k<3)
printf("Dynamic\n");
else
{
for(i=0;i<(k-2);i++) // checking the condition
{
if(!(fre[i]==fre[i+1]+fre[i+2])) / if match failed the printing not
{
printf("Not\n");
break;
}
}
if(i==(k-2)) // if the aforsaid loop executed totally then the string is dynamic
printf("Dynamic\n");
}
}
Suppose we are give two strings 'x' and 'y' of same length p (1 <= p <= 200000). Each string consists of atmost 3 distinct characters. These 3 distinct characters are same in both string. I want to find number of indices j such that x[j]=y[j] between a suffix of string 'x' of length l and prefix of string 'y' of same length l. I want to print answer for each l (1<=l<=p). For example: x : "dfgd" and Y : "gfdf". Answer for suffix of length 3 of string x and prefix of length 3 of string y is 1.I have to print answer for each l (1<=l<=p). Any suggestions?
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: I, II, problems same as BIT, Problem, Problem/HLD is used as well/
Z algorithm : Tutorial, Problem, Tutorial, Tutorial, problems same as KMP.
Floyd Warshall Algorithm : Tutorial, Implementation, Problem, Problem
Sparse Table (LCP, RMQ) : Tutorial, Problems, Tutorial, Implementation(C++), Java implementation
Heap / Priority Queue / Heapsort : Implementation, Explanation, Tutorial, Implementation, Problem, Chapter from CLRS
Binomial coefficients (nCr % M): Tutorial, Tutorial, Paper, Problem
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
Mo's Algorithm : Tutorial and Problems
Please help me in this;
Let's say I have n inputs $a_1$, $a_2$, $a_3$, $a_4$, $a_5$, ..., $a_n$
I have a vector vector<unsigned long long int> v
What should I do if I do not want to input $a_i$ in v is value of $a_i$ already exist in v
Problem is n is very large and elements can have a range of $0-10^9$
Can someone please tell me where I am wrong . Here is my code. I maintained 2 segment trees for maximum query and for sum query and then I found lower bound of prefix sum for the interval where my sum/2 lies . Please someone reply :( what is the error in my code
Hi, I am getting wrong answer for krillin is dead again https://www.codechef.com/viewsolution/18909176 Can anyone say me where I am getting it wrong. Thanks in advance.
I have passed Class X with basic knowledge of Java Code. I am willing to invest time in CodeChef competitions. Will Code Chef Certification Carry some recognition when I apply for UG Colleges (in India / Abroad) after Class XII. Pls help. Good Luck
Hello.
I think there are some serious issues with the testcases provided in TLG.
The input instruction says :
" The first line of the input will contain a single integer N (N ≤ 10000) indicating the number of rounds in the game. Lines 2,3,...,N+1 describe the scores of the two players in the N rounds. Line i+1 contains two integer Si and Ti, the scores of the Player 1 and 2 respectively, in round i. You may assume that 1 ≤ Si ≤ 1000 and 1 ≤ Ti ≤ 1000. "
Because of the constraints i added something like this to my code,
if(N > 10000) || if(Si < 1 || Si > 1000) || if(Ti < 1 || Ti > 1000) then Exit(0);
But the compiler kept rejecting my answer returning WA. I couldn't understand what was going on and then after wasting a whole day's time when i came across link text comment by @beroul i took the test case but it gave nothing as in last line score of p2 is zero.
Afterwards, just to try my luck i removed all the input constraints from my code and it works just fine. Are we not supposed to check whether an input meets the declared constraints or not? If so, what the above quote means and how a testcase that doesnot follow the instructions was given? Or maybe i am mis-understanding something. Please point it out to me.
Any answer is much appreciated. Thank you for your time. :)
can someone explain this problem in O(n*n) running time. My solution is getting TLE.
EASY MEDIUM
Binary Search, Greedy
N students are standing at distinct points in the X-axis. Every students will start running at t = 0. assign direction (left/right) to each of them such that the first time when any two students cross each other is as large as possible. Speed of every students is given.
Do binary search on the time. Suppose at any step in the binary search, we are are trying to find whether it is possible to assign direction such that no students will cross before some time say t.
To check, whether it is possible to assign direction. We fix the direction of leftmost students towards left (without loss of generality). For every other student from left to right, we try to fix the direction to left itself if it crosses non of the students before time t. And move to next student.
If it is not possible, we try to fix the direction as right. If it is possible then move to next student.
If we are able to assign direction to each students in that manner then the answer is yes, otherwise it is not possible.
For required precision, iterating 100 steps in the binary search is enough. Let's say the number of steps be S.
$O(S N)$ per test case.
$O(N)$
int main() { int i,j,n,t,a,b; float p=0.0,q=0.0,r=0.0; scanf("%d",&t); for(i=0;i<t;i++) {scanf("%d%d%d",&n,&a,&b); int k=(int)malloc(nsizeof(int)); for(j=0;j<n;j++) {scanf("%d",(k+j));} if(a==b) {for(j=0;j<n;j++) { if((k+j)==a) q++;
}p=((q*q)/(n*n));
}
else
{for(j=0;j<n;j++)
{
if(*(k+j)==a)
q++;
else if(*(k+j)==b)
r++;
}p=((q*r)/(n*n));
}printf("%f",p);
q=0.0;
r=0.0;
}return 0;
}