please suggest efficient algorithm
write a program to generate unique substrings(contains only unique characters) of given string.
Getting started here, questions about strategy, etiquitte, etc.
Hi guys.
I've just started here, I have a few questions about how I approach this place. Firstly, let me just say that wow - some of the problems here are pretty difficult, even for easy!
Alright, so I've just bunch of the questions in the FAQ, here's a few more.
What's the etiquette for posting here? For example are 'I'm working XYZ practice problem, I've got TLE error, here's my code, what should I do?' questions ok?
What's the general strategy for solving problem, or doing time optimization? Are there any tools that you use? Like, one of the things I can see that would be problematic, is when you get a 'wrong answer' but you don't know what the 'expected vs output' is. Is this just something you need to deal with as a programmer, to think of the corner cases yourself?
Is there any way to get additional test data?
How do you organise your code chef files in your IDE? For example, your class name (in Java) must called Main, and it can't be part of any package, when you paste in to the submitter, otherwise it'll give you an error, wondering how people deal with that.
code reusablity - I get the feeling that a lot of this is going to be using various appropriate algorithms. What I would tend to do is import the package that contains the algorithm. But given that the submission has to be a single file with no non-native imports, is the only thing you can do, is copy the code in for each algorithm?
Where would you start in terms of first problems to solve? For example I would suggest doing the Enormous Input test as one of your first problems.
.
TEST - Editorial
PROBLEM LINK:
Author:ADMIN
Editorialist:SUSHANT AGARWAL
DIFFICULTY:
CAKEWALK
PREREQUISITES:
Basic looping,Basic Input/Output
PROBLEM:
Rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
EXPLANATION:
Please refer to the sample solution given by editorialist.
EDITORIALIST'S SOLUTION:
Editorialist's solution can be found here.
Please help me with this code (TTENIS)
Here is my code: Solution
The expected output is also produced and the limits of the variables is also satisfied. The output format is also correct. Is it that we don't have to print leading zeros? Please help me with the code.
Thanks a lot!
Smart Pointer C++
Is there a way to utilize smart pointers from C++ in code chef? I have a binary tree that utilizes smart pointers. It compiles and runs just fine on X-code, mac compiler, but when I tried to run the program on Code Chef, i get this error.
prog.cpp:24:14: error: ‘shared_ptr’ in namespace ‘std’ does not name a template type
std::shared_ptr<TreeNode> left;
^~~~~~~~~~
It's just a pointer to the left node of the tree.
Same Problem listed in partially solved and practice section
Codechef's new feature of partial solving, which segregates partially solved problems from completely solved ones still has this one issue. I have 2 problems in the partially solved section which I solved completely. But as it turns out the problems now appear both in partially solved and practice section of my solved problems list. It's causing more confusion if anything else. Please get this corrected as soon as possible.
Computing Factorials of a huge number in C/C++: A tutorial
Hello @all,
As in MARCH13 contest we needed to use primary school arithmetics once again, and as it is a topic that comes up quite frequentely here in the forums thanks to this problem, and also, as I don't see a complete and detailed tutorial on this topic here, I decided I'd write one before my Lab class at university :P (spending free time with Codechef is always a joy!!)
- Some preliminary experiences with C
If we want to implement a factorial calculator efficientely, we need to know what we are dealing with in the first place...
Some experiences in computing factorials iteratively with the following code:
#include <stdio.h>
long long int factorial(int N)
{
long long ans = 1;
int i;
for(i=1; i <= N; i++)
ans *= i;
return ans;
}
int main()
{
int t;
for(t=1; t <= 21; t++)
{
printf("%lld\n", factorial(t));
}
return 0;
}
will produce the following output on Ideone:
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
-4249290049419214848
So, we can now see that even when using the long long data type, the maximum factorial we can expect to compute correctly, is only 20!
When seen by this point of view, suddenly, 100! seems as an impossible limit for someone using C/C++, and this is actually only partially true, such that we can say:
It is impossible to compute factorials larger than 20 when using built-in data types.
However, the beauty of algorithms arises on such situations... After all, if long long data type is the largest built-in type available, how can people get AC solutions in C/C++? (And, as a side note, how the hell are those "magic" BigNum and variable precision arithmetic libraries implemented?).
The answer to these questions is surprisingly and annoyingly "basic" and "elementar", in fact, we shall travel back to our primary school years and apply what was taught to most of us when we were 6/7/8 years old.
I am talking about doing all operations by hand!!
- The underlying idea behind long operations and how to map it into a programming language
12*11 = 132
Any programming language will tell you that. But, so will any 8 year old kid that's good with numbers. But, the kid's way of telling you such result is what we are interested in:
Here's how he would do it:
12
x 11
---------
12
+12
----------
132
But, why is this idea way more interesting than simply doing it straighforwardly? It even looks harder and more error-prone... But, it has a fundamental property that we will exploit to its fullest:
The intermediate numbers involved on the intermediate calculations never exceed 81
This is because it is the largest product possible of two 1-digit numbers (9*9 = 81), and these numbers,well, we can deal with them easily!!
The main idea now is to find a suitable data structure to store all the intermediate results and for that we can use an array:
Say int a[200] is array where we can store 200 1-digit numbers. (In fact, at each position we can store an integer, but we will only store 1 digit for each position.)
So, we are making good progress!! We managed to understand two important things:
- Primary school arithmetic can prove very useful on big number problems;
- We can use all built-in structures and data-types to perform calculations;
Now, comes up a new question:
How can we know the length of such a huge number? We can store an array and 200 positions, but, our big number may have only 100 digits for example.
The trick is to use a variable that will save us, at each moment, the number of digits that is contained in the array. Let's call it m.
Also, since we want only one digit to be stored in every position of array, we need to find a way to "propagate" the carry of larger products to higher digits and sum it afterwards. Let's call the variable to hold the carry, temp.
- m -> Variable that contains the number of digits in the array in any given moment;
- temp -> Variable to hold the "carry" value resultant of multiplying digits whose product will be larger than 9. (8*9 = 72, we would store 2 on one array position, and 7 would be the "carry" and it would be stored on a different position.)
So, now that we have an idea on how to deal with the multiplications, let's work on mapping it into a programming language.
- Coding our idea and one final detail
Now, we are ready to code our solution for the FCTRL2 problem.
However, one last remark needs to be done:
How do we store a number in the array, and why do we store it the way we do?
If after reading this tutorial you look at some of the accepted solutions in C/C++ for this problem, you will see that contestants actually stored the numbers "backwards", for example:
123 would be saved in an array, say a, as:
a = [3,2,1];
This is done such that when the digit by digit calculations are being performed, the "carry" can be placed on the positions of the array with higher index. This way, we are sure that carry is computed and placed correctly on the array.
Also, computing the products this way and maintaining the variable, m, allows us to print the result directly, by looping from a[m-1] until a[0].
As an example, I can leave here an implementation made by @upendra1234, that I took the liberty to comment for a better understanding:
#include<stdio.h>
int main()
{
int t;
int a[200]; //array will have the capacity to store 200 digits.
int n,i,j,temp,m,x;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
a[0]=1; //initializes array with only 1 digit, the digit 1.
m=1; // initializes digit counter
temp = 0; //Initializes carry variable to 0.
for(i=1;i<=n;i++)
{
for(j=0;j<m;j++)
{
x = a[j]*i+temp; //x contains the digit by digit product
a[j]=x%10; //Contains the digit to store in position j
temp = x/10; //Contains the carry value that will be stored on later indexes
}
while(temp>0) //while loop that will store the carry value on array.
{
a[m]=temp%10;
temp = temp/10;
m++; // increments digit counter
}
}
for(i=m-1;i>=0;i--) //printing answer
printf("%d",a[i]);
printf("\n");
}
return 0;
}
I hope this tutorial can help someone to gain a better understanding of this subject and that can help some people as it is why we are here for :D
Best Regards,
Bruno Oliveira
EDIT: As per @betlista comment, it's also worth pointing out that, since we keep only a single digit at each position on the array, we could have used the data-type char instead of int. This is because internally, a char is actually an integer that only goes in the range 0 - 255 (values used to represent the ASCII codes for all the characters we are used to see). The gains would be only memory-wise.
Package Problem(In Java)
You want to send your friend a package with different things. Each thing you put inside the package has such parameters as index number, weight and cost. The package has a weight limit. Your goal is to determine which things to put into the package so that the total weight is less than or equal to the package limit and the total cost is as large as possible.
You would prefer to send a package which weights less in case there is more than one package with the same price.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. The input file contains several lines. Each line is one test case.
Each line contains the weight that the package can take (before the colon) and the list of things you need to choose. Each thing is enclosed in parentheses where the 1st number is a thing's index number, the 2nd is its weight and the 3rd is its cost. Eg:
81 : (1,53.38,$45) (2,88.62,$98) (3,78.48,$3) (4,72.30,$76) (5,30.18,$9) (6,46.34,$48) 8 : (1,15.3,$34) 75 : (1,85.31,$29) (2,14.55,$74) (3,3.98,$16) (4,26.24,$55) (5,63.69,$52) (6,76.25,$75) (7,60.02,$74) (8,93.18,$35) (9,89.95,$78) 56 : (1,90.72,$13) (2,33.80,$40) (3,43.15,$10) (4,37.97,$16) (5,46.81,$36) (6,48.77,$79) (7,81.80,$45) (8,19.36,$79) (9,6.76,$64)
OUTPUT SAMPLE:
For each set of things that you put into the package provide a list (items’ index numbers are separated by comma). E.g. 4 - 2,7 8,9
CONSTRAINTS:
Max weight that a package can take is ≤ 100 There might be up to 15 items you need to choose from Max weight and cost of an item is ≤ 100
TLG - Editorial
PROBLEM LINK:
Author:ADMIN
Editorialist:SUSHANT AGARWAL
DIFFICULTY:
EASY
PREREQUISITES:
Basic looping,Arrays
PROBLEM:
At the end of each round the leader and her current lead are calculated. Once all the rounds are over the player who had the maximum lead at the end of any round in the game is declared the winner.
EXPLANATION:
Create two arrays(Player1-Stores the scores of player 1 in all the rounds)[a1,a2,a3....an] and (Player2-Stores the scores of player 2 in all the rounds)[b1,b2,b3...bn].
Create a third array "Lead" such that the i'th element of Lead is ((a1+a2...+ai) - (b1+b2...bi)). Create a fourth array "modulus lead" such that the i'th element of this array is the modulus of the i'th element of "Lead".
Find the maximum element of "modulus lead".This is the maximum lead attained by the winner.If the element in the corresponding position of "lead" is positive then player 1 is the winner,otherwise player 2 is.
EDITORIALIST'S SOLUTION:
Editorialist's solution can be found here.
Invitation to ATMOS Codejam
Hello everyone!
I am delighted to invite you all for ATMOS CodeJam Qualifiers held as a part of the technical fest, ATMOS , organized by our institute BITS-Pilani, Hyderabad Campus.
The contest is unrated at the moment, but we're in talks to keep it rated. The contest will be of 2 hours and you will be given five questions of varying difficulty (Cakewalk to Hard). We have tried our best to include problems such that even novice coders can attempt some problems while even best coders feel stuck at some. It is advised to read the problem statements carefully and have some practice to brush up your skills :) .
Contest Link (codechef) : https://www.codechef.com/contests
Contest Link (ATMOS Homepage) : https://bits-atmos.org/events/codejam
The problems have been set and tested by @rock7lee , @ashishgup, @mahir111 , @icy_noctiluca and @vijju123 .
Scoring-
With ICPC around the corner it is unanimously decided to use ACM-ICPC pattern of scoring. There will be no partial points for a problem.
Whats in it for you?
We have decided to keep monetary prizes for top 3 competitors this time.
The distribution is as follows-1
- Rank 1- Rs 7,500
- Rank 2- Rs 4,500
- Rank 3- Rs 3,000
In addition, we have decided to give following benefits as well-
- Top 25 participants get selected to Final On-site Round during ATMOS.
- Top 15 participants will be eligible for free Accommodation and their Registration Fees will be waived.
However, to be eligible for prizes, you need to register at our ATMOS website here and fill this google doc.
Further, on-site presence is necessary to claim the cash prizes for both online and on-site rounds. In case an eligible candidate is not present to accept the prize/perks of the online round, the next available candidate on the rank-list will avail the same.
Lastly, we think it will serve as a good opportunity to practice for upcoming ICPC as well. :)
Contest Details-
Duration- 2hrs
Start Time- 20:30 hrs, IST on 15th October, 2017.
End Time- 22:30 hours, IST on 15th October, 2017.
You compulsorily need a Codechef handle in order to participate!!
ACM-ICPC India Overnite Multi-Provincial Programming Contest
The icpc.baylor.edu site is showing a new Upcoming Regional as ACM-ICPC India Overnite Multi-Provincial Programming Contest.
Registrations are open. 3 teams are also found to be accepted as of 13th October,2017
however the local website seems to be of Kshitij - the annual techno-management fest of IIT Kharagpur.
We haven't seen anything like this in previous years. Neither is anything mentioned about this in the CodeChef 2018 ICPC wiki
Maybe the CodeChef team or someone from IIT Kharagpur-Kshitij can throw some more light on this ?
Thanks.
PS: Please don't spam the question with unnecessary comments as those may confuse newer teams participating for the first time this year.
SEACO - Editorial
PROBLEM LINK:
Author:Sergey Nagin
Tester:Jingbo Shang
Editorialist:Hanlin Ren
DIFFICULTY:
Easy-Medium
PREREQUISITES:
Fenwick tree, difference array
PROBLEM:
You're given an array $a$ consisting of $n$ zeros initially. You need to perform two kinds of commands:
- Add $1$ to $a[l\sim r]$;
- Perform all commands whose indices are in $[l,r]$, where $r<$(the index of current command)
After performing these commands, output the final array.
QUICK EXPLANATION:
For each command, we need to count how many times it's executed during the whole process, denoted by $cnt[i]$. We can iterate the commands backwards, and every time we meet a command $2\ l\ r$ which is executed $k$ times, we add $k$ to $cnt[l\sim r]$. When we know $cnt[i]$ for every command $i$ of type $1$, we can easily figure out the answer by maintaining the difference array of $a$.
EXPLANATION:
subtask 1
brute force
We have $n,m\le 10$ and we can use brute force. We just write a procedure op(i)
that performs the $i$-th operation, and do what the problem asks us to do:
op(i) :
if type[i] == 1 then
for j = l[i] to r[i] do
a[j] += 1
else //type[i] == 2
for j = l[i] to r[i] do
op(j)
a faster algorithm
Let $f_{i,j}$ be the number of time that $a[j]$ was increased when performing operation $i$.
For the first type, $f_{i,j}$ is very easy to compute: if $l_i\le j\le r_i$, then $f_{i,j}=1$, otherwise $f_{i,j}=0$.
For the second type, a single operation $i$ should be equivalent to the sum of all operations indexed in $[l_i,r_i]$. So for any $j$, $f_{i,j}$ is the sum of $f_{k,j}$'s where $l_i\le k\le r_i$.
Once we know for every command, how many contribution it does to every element in array, we can compute the answer. Pseudocode:
f = [empty array of m*n]
for i = 1 to m do
if type[i] == 1 then
for j = l[i] to r[i] do
f[i][j] = 1
else
for k = l[i] to r[i] do
for j = 1 to n do
f[i][j] = f[i][j] + f[k][j]
//perform this operation
for j = 1 to n do
a[j] = a[j] + f[i][j]
The total time complexity is $O(nm^2)$.
subtask 2
Let $cnt[i]$ be the number of times that command $i$ is executed. If we know $cnt[1\sim m]$, this problem will become much easier.
How to compute $cnt[]$? We don't know $cnt[1]$ but we know $cnt[m]$ must be $1$. If the command $m$ is of the form $2\ l_m\ r_m$, then $cnt[l_m\sim r_m]$ will increase by $1$. Then we look at command $m-1$: originally its $cnt$ is $1$, however if it's executed by command $m$ then its $cnt$ should be $2$. Also this command might influence other $cnt[]$'s as well: if it's of the form $2\ l_{m-1}\ r_{m-1}$, then $cnt[l_{m-1}\sim r_{m-1}]$ will increase by $cnt[m-1]$. Next we can consider $cnt[m-2]$ and the same things happen again and again...
This gives us an algorithm to compute $cnt[]$. Initially all $cnt[i]$'s should be $1$. Let's then iterate the commands backwards. When we process a command $i$, if it's of the form $2\ l\ r$, we add $cnt[i]$ to $cnt[l\sim r]$. Pseudocode:
cnt = [array of 1's]
for i = m downto 1 do
if type[i] == 2 then
for j = l[i] to r[i] do
cnt[j] += cnt[i]
Once we know all $cnt[]$'s, for any command $i$ of the form $1\ l\ r$, we simply add $cnt[i]$ to $a[l\sim r]$.
The overall time complexity is $O(nm)$.
subtask 3
We need to optimize the code above. When we need to add the same value on a segment, we may consider maintaining its difference sequence. Formally, let $dcnt[i]=cnt[i]-cnt[i+1]$, then adding $c$ to $cnt[l\sim r]$ is equivalent to:
- $dcnt[r] \gets dcnt[r]+c$;
- $dcnt[l-1]\gets dcnt[l-1]-c$.
When we're dealing with command $i$, $cnt[i\sim M]$ is fixed(there won't be modifications on them anymore). Thus we can calculate $cnt[i]$ immediately, using the formula $cnt[i]=dcnt[i]+cnt[i+1]$. As we obtained $cnt[i]$, we can update the array $dcnt[]$ when $i$-th operation is type $2$. Pseudocode:
dcnt = [array of 0's]
cnt[m + 1] = 1
for i = m downto 1 do
cnt[i] = dcnt[i] + cnt[i + 1]
if type[i] == 2 then
dcnt[r[i]] += cnt[i]
dcnt[l[i] - 1] -= cnt[i]
This gives an $O(m)$ algorithm for computing $cnt[]$.
We can use the same trick to obtain the final array: let $da[i]=a[i]-a[i+1]$, then adding $c$ to $a[l\sim r]$ is equivalent to:
- $da[r]\gets da[r]+c$;
- $da[l-1]\gets da[l-1]-c$.
After all modifications are done, we calculate the suffix sum of $da$, and that's the array $a$ we want. Pseudocode:
da, a = [array of 0's]
for i = 1 to m do
if type[i] == 1 then
da[r[i]] += cnt[i]
da[l[i] - 1] -= cnt[i]
for i = n downto 1 do
a[i] = a[i + 1] + da[i]
The overall complexity is $O(n+m)$.
ALTERNATIVE SOLUTION:
To maintain $cnt[]$, you need to support two operations: adding on a segment and querying on one position. Since this problem has some special structure, it can be done in linear time. Generally such kind of problems can be solved in time $O(m(\log m+\log n))$, if you use data structures such as segment trees or Fenwick trees.
If your solution is different with ours, feel free to leave a comment.
AUTHOR'S AND TESTER'S SOLUTIONS:
Tester's solution can be found here.
Editorialist's solution can be found here.
ISTA2001 - Editorial
Setter: Istasis Mishra
Tester: Udit Sanghi
This would be an apology rather than an editorial. You can find the solution by just googling "Cuboid ant". I deeply regret that I have put up this problem up for this contest. It was brought to my attention that this problem's solution is googlable 2.5 hours into the contest.
I hope the community will accept my apology and I promise this won't happen again. I will make sure my problems are original from now on and only then put it up for a contest. :)
Author's solution:here
RAJAPR0 - Editorial
Contest:ICO 2018 Practice Contest 1
Author:Shashwat Goel
Tester:Udit Sanghi
Editorialist:Shashwat Goel
Problem Statement
Given a graph with $N$ vertices and $N-1$ edges and $Q$ queries, you have to find the parity of path length from a node $A$ to node $B$ for each query.
Explanation
Theorem: Any connected graph with $N$ vertices and $N−1$ edges is a tree. Proof Let $G$ be a connected graph with $N$ vertices and $N − 1$ edges. We show that $G$ contains no cycles. Assume to the contrary that $G$ contains cycles. Remove an edge from a cycle so that the resulting graph is again connected. Continue this process of removing one edge from one cycle at a time till the resulting graph $H$ is a tree. As $H$ has $N$ vertices, so number of edges in $H$ is $N−1$. Now, the number of edges in $G$ is greater than the number of edges in $H$. So $N−1 > N−1$, which is not possible. Hence, $G$ has no cycles and therefore is a tree.
Therefore the given graph is a tree (note that the above proof is a basic property of a tree and questions like these assume you know this).
Now, since it's a tree, the shortest path between 2 nodes can be calculated by dfs/bfs. This gives you an $O(NQ)$ solution, which solves the first subtask.
Now moving for the second subtask, one must notice that the distance between 2 nodes of a tree is given by
(FORMULA 1): $$\text{Depth of starting node} + \text{Depth of Final node} - 2 \times \text{Depth of Lowest Common Ancestor}$$ This is evident if you draw some trees. The depth is the distance of a node from the root.
In this question, we can fix any node as the root (because the tree is bidirectional, if you change the root the orientation of the tree changes but everything else remains the same). So we fix a root and pre compute the LCA of all pairs of vertices (in $O(N)$ or $O(LogN)$). Then we can answer the Queries in $O(1)$ by checking the parity of Formula 1. This solution takes $O(N^2)$ time for precomputation and $O(1)$ for the queries. It therefore works on Subtask 2. This however doesnt work for subtask 1.Now notice that subtask 1 and 2 are exclusive, one has a low number of nodes and high number of queries while the other has a high number of nodes and low number of queries. So we use them exclusively in our code, that is check if $N>10^3$, then do the first method otherwise second.
Now, there is an algorithm for computing the LCA: Link
Now if you can code the $O(LogN)$ computation in the above link, You can simply find the LCA for every query without having to precompute anything. This solution works for all of the above, subtask 1 2 and 3.
But here is the fun part. The actual solution is much easier, and does not require computation of the LCA in this particular problem. There is just one clever observation:
Notice formula 1 again.
$$\text{Length of Path}=D[U]+D[V]-2*D[LCA]$$
Notice that $2*D[LCA]$ is always even. Also notice that when an even number is subtracted/added from a number, it does not change the numbers parity, i.e. Odd+-Even = Odd and Even+- Even=Even. So we can eliminate this term. THUS, the answer is independent of the LCA and WE DO NOT NEED TO COMPUTE IT!
You simply find the parity of $D[U] + D[V]$ and you're done!
So conclusion: The final algorithm requires a single DFS precomputation to compute the depth of each node. Then taken the queries and just check if $D[U]+D[V]$ is odd or even and output it.
Tester Solution: here
TIDUAFT - Editorial
Contest:ICO 2018 Practice Contest 1
Author:Udit Sanghi
Tester:Shashwat Goel
Editorialist:Shashwat Goel
Problem Statement
Given $3$ numbers $N$,$X$ and $K$ you need to tell the number of ways of making an array of size $N$ with all numbers being positive $\leq 100$ with number $X$ appearing exactly $K$ times where every adjacent pair of integers are coprime.
Explanation
We can straight away write a brute-force for subtask 1.
Notice that for each element, the next element must be a number coprime to it, so if we can make a list of all coprimes to all numbers less than $100$, we can use this list to find the next number every time.
We do this by running an $O(N^2)$ Precomputation using $O(N^2)$ memory to store a list of numbers coprime to $i$ in $cop[i]$.
Now, we run $N$ loops. The first loop fixes the first element say $A$. The second loop iterates over the elements coprime to $A$, say $B$. The third loops iterates over the elements coprime to $C$, and similarly for $n=4$. This way we can generate all possible $4$ element combinations, we just need to count the number of combinations in which the value $X$ came exactly $K$ times.
This is sufficient for subtask 1.
Subtask 2 requires us to apply a little more math (combinatorics).
Since $\dfrac{N+1}{2}$ positions are filled and $N$ is odd, we can only do this by filling $X$ in alternating positions. This leaves $\dfrac{N-1}{2}$ positions empty. In each of these positions, we can fill any of the numbers coprime to $X$ and all conditions will be satisfied. So we have to fill $\dfrac{N-1}{2}$ positions with $cop[x].size()$ elements, the possibilities of this are $cop[x].size()^\frac{N-1}{2}$ giving us an $O(N)$ [Naive] and $O(LogN)$ [using fast exponentiation]
Both pass, so you can do any of the above.
Now comes the real part of the question, Subtask 3.
We are going to use dynamic programming to solve the problem. Let the dp states be, $dp[ind][curr][numofxs]$, that is, from index $0$ to $ind$, how many ways to select $numofXs$ ‘X’ and keep the value of $arr[ind]$ as $curr$. One can notice that if $curr$ is not equal to $X$, this is equal to the sum of all $dp[ind-1][Y][numofXs]$ for $Y = 1$ to $100$, and $Y$ co-prime to $curr$. This is because, for the we can simply append $curr$ to all the arrays built till $ind-1$. If $curr = X$, the $numofXs$ has increased by 1 so we take the summation of $dp[ind-1][y][numofXs-1]$ for $Y = 1$ to $100$ and $Y$ coprime to $curr$ (or $X$ for this case). We could precompute a coprime boolean array in $N^2$ to store which pairs are coprime, but this only reduces the complexity by $log(N)$ and is not necessary to pass the constraints.
"I want to ask a question" - Ask them all here!
Hello guys,
UPDATE- This thread is in case you dont have enough karma to ask questions.
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
SEAVOTE - Editorial
PROBLEM LINK:
Author:Sergey Nagin
Tester:Shiplu Hawlader
Editorialist:Lalit Kundu
DIFFICULTY:
EASY-MEDIUM
PRE-REQUISITES:
Maths
PROBLEM:
Sereja conducted a voting about N of his opinions. Ai percent of people voted for opinion number i. This statistics is called valid if sum of all Ai is equal to 100.
Now let us define rounding up of a statistics A.
- If Ai is not an integer, it will be rounded up to next integer.
- Otherwise it will be left as it is.
Now let us consider a statistics B of size N in which each of Bi is an integer. Now he wants to know whether there exists some valid statistic A of size N (may contain real numbers) such that after rounding it up, it becomes same as B?
1 ≤ N ≤ 10000EXPLANATION:
Let's define a small positive infinitesimal quantity e(epsilon).
For Bi, corresponding element in array A can be in range [Bi-1+e,Bi](both ranges included).
However, Bi = 0, the above range is invalid, so we'll ignore all zero elements. Let's say size of the remaining array B(after removing 0s) is N.
We now consider the lower and upper bounds on the sum of all numbers in A(note: any real number between these bounds can be generated). So, if 100 lies within these bounds, then answer is yes.
LOWER BOUND:
Now, what is the minimum possible sum? It's S = [sum over all Bi] - N(number of non-negative elements in B) + e. So, we get condition for validity that S ≤ 100. If we ignore the e, we get S = [sum over all Bi] - N(number of non-negative elements in B) < 100.
UPPER BOUND:
Now, what is the maximum possible sum? It's S = sum over all Bi. So, we get one more validity condition that S ≥ 100.
Complexity: O(N).
SOLUTIONS:
Setter's solution
Tester's solution
Note: Some people were confused about bounds on array A. A was not even in input.
Invitation to Inscription '17
Engineer, the annual technical fest of NITK, Surathkal, in association with HackerEarth presents Inscription, the online algorithmic programming contest of NITK. It is also the flagship event of Engineer's Computer Science Events' Committee. The previous editions of the event witnessed tons of participants from various countries and also successfully managed to attract some of the best coders of the world to compete for the top spot. This year once again Inscription strives to achieve its previous glory.
The details of the competition are as follows:
Timings : 09:00 PM IST (14-OCT-17) to 02:00 AM IST (15-OCT-17) (Check your timezone here)
Contest Link :https://www.hackerearth.com/inscription-17
Prizes only for top 3 Indian winners.
- First Prize : 10000 INR
- Second Prize : 6000 INR
- Third Prize : 4000 INR
To be eligible for prizes, please fill the form : https://goo.gl/forms/QmDYxuLFWIE06x572
RULES:
1. This is an individual contest.
2. You will receive hundred points for solving a problem (passing all test cases — no partial credit), regardless of the level of difficulty of that problem.
3.The total time is the sum of the time consumed for each problem solved. The time consumed for a solved problem is the time elapsed from the beginning of the contest to the submittal of the first accepted run plus 20 penalty minutes for every previously rejected run for that problem. There is no time consumed for a problem that is not solved.
We have tried our best to create an interesting problemset, and we hope that everyone finds something interesting in the tasks. Editorials will be published for all of them at the end of the contest.
Here is the link to : Inscription '16
We hope you'll have an amazing time! Happy Coding!! :)
ACM ICPC IIITM Gwalior Website Down
Hey Guys!
Me and my friends are looking to register on IIITM Gwalior, but their website http://icpc-iiitm.com returns Error 509 (Bandwidth Limit Exceeded) Any Idea/Suggestions on how to proceed forward with registration? Don't want to miss the deadline because of it. We have registered on the baylor website and requested our coach to register our team for us. Since this is our first time with ICPC there might be many small details we don't know of which could be useful.
Thank You!!
MAXDIFF - Editorial
PROBLEM LINK:
Author:Vamsi Kavala
Tester:Hiroto Sekido
Editorialist:Anton Lunyov
DIFFICULTY:
CAKEWALK
PREREQUISITES:
Greedy algorithm, Sorting algorithms
PROBLEM:
You are given an array W[1], W[2], ..., W[N]. Choose K numbers among them such that the absolute difference between the sum of chosen numbers and the sum of remaining numbers is as large as possible.
QUICK EXPLANATION:
There are two possibilities to try - K largest numbers and K smallest numbers (see below why). So the solution could be like this:
- Sort all numbers.
- Find the sum of all numbers. Let it be S.
- Find the sum of first K numbers. Let it be S1.
- Find the sum of last K numbers. Let it be S2.
- Output max(abs(S1 − (S − S1)), abs(S2 − (S − S2))) as an answer.
EXPLANATION:
Consider the following sub-problem: choose K numbers with largest possible sum. Then the solution obviously is K largest numbers. So that here greedy algorithm works - at each step we choose the largest possible number until we get all K numbers.
In our problem we should divide the set of N numbers into two groups of K and N − K numbers respectively. Consider two cases:
The group with largest sum, among these two groups, is group of K numbers. Then we want to maximize the sum in it, since the sum in the second group will only decrease if the sum in the first group will increase. So we are now in sub-problem considered above and should choose K largest numbers.
The group with largest sum, among these two groups, is group of N − K numbers. Similarly to the previous case we then have to choose N − K largest numbers among all numbers.
This reasoning justify the solution in the QUICK EXPLANATION.
Regarding implementation details. Since N and T are small, then every simple O(N2) sorting algorithm from here will work. Other steps of the solution seems trivial to implement.
ALTERNATIVE SOLUTION:
Let's go further and ask our self which of two above cases actually gives the answer. After short thinking it became clear that larger difference would be when more numbers are included to the group of largest numbers. Hence we could set M = max(K, N − K), find the sum of M largest numbers (let it be S1) and then the answer is S1 − (S − S1), where S is the sum of all numbers.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution will be provided soon.
Tester's solution can be found here.
RELATED PROBLEMS:
Will be provided soon. All readers are welcomed to provide related problems in comments.