For eg. 2341 then we subtract the adjacent terms with each 2-3=1 2-4=1 4-1=3 then after subtracting we get :113 then we minus 1-1=0 1-3=2 that is the single term which is 2 this must be the answer. Please tell the Logic For code
Please tell me the logic for the code.
Output is correct but getting wrong answer during submission.
http://discuss.codechef.com/problems/ERROR
include<stdio.h>
include<string.h>
int main() { int i,t; scanf("%d",&t); for(i=1;i<=t;i++) { int len,j,k,l,flag=0,count1=0,count2=0,count3=0;; char num1[100001]; char num2[3]; char sample1[3]={'1', '0', '1'}; char sample2[3]={'0', '1', '0'}; scanf("%s", num1); len=strlen(num1); for(j=0;j<len-2;j++) {
for(k=j;k<=j+2;k++)
{
num2[count1]=num1[k];
count1++;
}
for(l=0;l<3;l++)
{
if(num2[l]==sample1[l])
count2+=1;
}
for(l=0;l<3;l++)
{
if(num2[l]==sample2[l])
count3+=1;
}
if(count2==3)
{
flag=1;
break;
}
else if(count2==3)
{
flag=2;
break;
}
count1=0,count2=0,count3=0;
}
if(flag==1 || flag==2)
printf("GOOD");
else
printf("BAD");
printf("\n");
}
return 0; }
my mergesort program does not perform sort what is the error i could not get it?
void merge(int L[],int R[],int A[]){
int nL=sizeof(L)/sizeof(L[0]);
int nR=sizeof(R)/sizeof(R[0]);
int i=0,j=0,k=0;
while(i<nL && j<nR){
if(L[i]<=R[j]){
A[k]=L[i];
i++;}
else{
A[k]=R[j];
j++;
}
k++;
}
while(i<nL){
A[k]=L[i];
i++;
k++;
}
while(j<nR){
A[k]=R[j];
j++;
k++;
}
}
void mergeSort(int A[]){
int n=sizeof(A)/sizeof(A[0]);
if(n<2)
return;
int mid=n/2;
int left[mid];
int right[n-mid];
for(int i=0;i<mid;i++)
{
left[i]=A[i];
}
for(int i=mid;i<n;i++){
right[i-mid]=A[i];
}
mergeSort(left);
mergeSort(right);
merge(left,right,A);
}
void printArray(int *A,int size){ for(int i=0;i<size;i++){ cout<<A[i]<<endl; }}
getting runtime error in c(sigabrt)
https://www.codechef.com/viewsolution/18906525 getting runtime error in this question https://www.codechef.com/problems/CLFIBD.please help
Majin Vegeta, VEGETA
I have tried this question, but I don't know why I am getting run time error. This is my source code: https://www.codechef.com/viewsolution/18906609 I am a beginner and I am stuck. Please help me correct this code. I am really thankful to you.
quickmatch 10 coming soon with 3 hiring companies
This time we have 3 hiring companies and good ones, good coders working in them...
Will update details once problems are ready. Readying it. https://www.codechef.com/KQ102018
Edit: Codechef to share 250 laddus to top contestants (number of tops depends on number of participants). Thank you codechef.
Ciel and A-B problem (why my solution is wrong?)
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; }
ipc programming club june contest
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.
somebody pls explain the author soln for shkstr question of june challenge
link for author soln is https://s3.amazonaws.com/codechef_shared/download/Solutions/JUNE18/setter/SHKSTR.cpp
CLFIBD - Editorial
PROBLEM LINK:
Author:Avijit Agarwal
Tester and Editorialist:Soumik Sarkar
DIFFICULTY:
CAKEWALK
PREREQUISITES:
Strings, Sorting
PROBLEM:
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$.
EXPLANATION:
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 AND TESTER'S SOLUTION:
Author's solution can be found here
Tester's solution can be found here.
New blog for Competitive Programmers
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
WRKWAYS - Editorial
Problem Link
Author:Noszály Áron
Tester:Misha Chorniy
Editorialist:Bhuvnesh Jain
Difficulty
MEDIUM
Prerequisites
Factroisation, Combinatorics
Problem
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.
Explanation
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.
Subtask 1: N ≤ 10, C ≤ 100
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.
Subtask 2, 3: N ≤ ${10}^6$, C ≤ ${10}^9$
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.
Editorialist Solution: Based on solutions by contestants in the contest (Greedy approach)
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.
Time Complexity
$O(N + (\text{number of prime factors of C}) * {\sigma_{0}{(C)}}^2)$ or $O(\sigma_{0}{(C)} * \log{C} + N)$
Space Complexity
$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 AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
Editorialist's solution can be found here.
Invitation to CodeChef June Cook-Off 2018 sponsored by ShareChat!
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:
- Problem Setter: barenuz (Igor Barenblat)
- Problem Tester: mgch (Misha Chorniy)
- Admin: kingofnumbers (Hasan Jaddouh)
- Problem Editorialist: vijju123 (Abhishek Pandey)
- Statement Verifier: xellos0 (Jakub Safin)
- Russian Translator: hloya_ygrt (Yuri Shilyaev)
- Mandarin Translator: huzecong (Hu Zecong)
- Vietnamese Translator: (VNOI Team)
Contest Details:
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!
New channel for Data Structures and Algorithms.
Krillin is dead AGAIN Problem Code
Can i get correct value of medium using this formula: 3median = 2mean + mode.
Or i have to explicitly figure out through element wise compare.
why am i getting wrong in the problem? each time it's saing wrong output .i have tried with all the inputs of my thoughts. problem== Home » Practice(Beginner) » Fibonacci String
//also i have checked by breaking the whole program in different funtions.
include<stdio.h>
include<stdlib.h>
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");
}
}
string similarity
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?
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: 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
Push unique array?
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$
krillin is dead help
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