Longest subsequence whose sum is divisible by k [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am practicing some Dynamic Programming problems and encounter this problem
Given an array of n(1<=n<=1000) integers and a positive integer k(k<=1000). Find the longest subsequence whose sum is divisible by k.
For example, a = [1,6,11,5,10,15,20,2,4,9] and k=5.
The result should be: [9,4,20,15,10,5,11,6] because 9+4+20+15+10+5+11+6 = 80, which is divisible by 5.
What is a suitable approach to solve this problem?

Start with the longest possible subsequence, the array itself. Calculate its sum modulo k. If its zero, we are done. Otherwise, find a number such that its modulo k is the same. If that exists, remove it and we are done. Otherwise keep going.

Brute Force Approach:
We can generate all the possible sub-sequences and then find the largest sub-sequence among them whose sum is divisible by K.
However, the time complexity of this approach will be O(n*n).
Efficient Approach:
We can use dynamic programming here. Kindly note that this approach will only work for small values of K.
dp[i][curr_mod] = max(dp[i + 1][curr_mod], dp[i + 1][(curr_mod + arr[i]) % m] + 1)
Here, dp[i][curr_mod] stores the longest subsequence of subarray arr[i…N-1] such that the sum of this subsequence and curr_mod is divisible by K.
At each step, either index i can be chosen to update curr_mod or it can be ignored.
Also, note that only SUM % m needs to be stored instead of the entire sum as this information is sufficient to complete the states of DP.

Related

Sum of all non-decreasing sequences with sum x and length k [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I tried to solve this problem my own, but I can't find any solution with faster time complexity for it.
I would much appreciate it if you could help me.
Here is the problem:
Consider all non decreasing sequences with length k and sum x. For each sequence a1,..,ak, we calculate the value a1^m+a2^m+...+ak^m (where m is given).
What is the total sum of this calculated sums mod 1e9+7. Constraints:
1<=n, m<=4096, 1<=k<=nTime limit(2 seconds) Memmory limit(256 mb).
I tried to solve it by dp and define dp[i][j][u] as the answer for length i and sum j and the last number u and update my dp with all dp[i-1][j-u][x] such that x is less than u my soution works in O(n^3*k) but it can be improved by partial sum to O(n^2*k) but this is also steal much slower than what the time limit is(2 sec) because of the large constraints.
This is what i implemented so far:
https://pastebin.ubuntu.com/p/Kx3j7WMVSv/
Do you have any suggestions to improve my codes time complexity.
You are new to this site, so even though this question should be downvotted (because there is no code to show us what you have done), I decided to add something important notes since I guess you may have missed this part.
Remember, you cannot do this simply by trying to calculate a1^m+a2^m+...+ak^m and then mod to 1e9+7. Because a1^m+a2^m+...+ak^m will be too big to keep it in any standard data types and this is probably an important point of this question.
In this case you need to use Modular arithmetic to calculate your result progressively. For example these will be useful for you:
if a ≡ b (mod n), then if a^2 ≡ b^2 (mod n) and if b^2 ≡ r (mod n) then a^2 ≡ r (mod n)
if a ≡ b (mod n), then if a*a ≡ b*a (mod n)
if a ≡ b (mod n), then if a+k ≡ b+k (mod n)
In addition, since 1e9+7 is prime, you can use prime number properties to progressively calculate your result. But I don't think it will be necessary here.
I won't post your answer, because you need to do most of work yourself, but you should be able to solve it correctly with this information.

How to count in binary in base 10 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I would like an integer in c++ to count up in binary like:
1, 10, 11, 100, 101, 110, 111
But i want to values to be in base 10 like:
one, ten, eleven, one hundred, one hundred and one, etc.
Basically count up in decimal but look like base 10.
Is there a algorithm to do this.
-Joseph
This is how you should proceed:
use a string for binary values to display it
you should implement a cycle which will end when your number reaches 0 and should write the result of currentValue % 2 to the start of your string then divide your number with 2
you should implement a function which will return the humanely readable number text, you might want to take inspiration from here, but a clue is that the digit number % 3 is relevant. If it is 0, then you will need to write the digit if the digit next to it to the left does not happen to be one, so values between 11-19 are an exception here and don't forget thousand, million, billion, if the modulo is 1, then you will have a special text, like eleven, ... nineteen, twenty, ..., ninety and if modulo is 2, then the text will be the digit + "hundred"
You will basically have a number and will be able to get the binary from it and the textual representation as well.
String is not necessary for the algorithm, one can cout a std::bitset as well.

Efficient algorithm to calculate all possible pair whose multiplication is a perfect quare [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have two numbers N and M.
I efficiently want to calculate how many pairs of a,b are there such that 1<=a<=N and 1<=b<=M and a*b is a perfect square.
I know the obvious N*M algorithm to compute this. But i want something better than that.
Thanks for any help in advance. A pseudo code will be more helpful.
EDIT : I think it can be done in a better time may O(m+n) or something like that but calculating new pairs directly from previous pairs rather than iterating over all a and b.
My approach would be this:
for s is quare and s <= N*M
Do a prime factorization of s.
iterate over the partitions of this prime factorization and check which ones fullfill your requirement
Iterating over the possible partitions may be a bit tricky, but I'm quite certain that this is the most efficient approach that is possible.
Iterating over square numbers, on the other hand, is trivial:
for(int i = 0, square = 0; /*whatever*/; square += 2*i++ + 1)
I would go for a way using prime decompositions.
Get a hold of all the prime numbers between 1 and max(N,M), and let us call them the (p0, p1, ... pn)
Then any number a <= N and b <= M can be written as and , for i from 1 to n, where the ai and bi can be any positive integer or 0.
Then, any product a*b can be written as , and the caracterization of a perfect square in that writing would be that all the (ai+bi) need to be even (0 is even, for the record).
Then you somehow need to iterate over all the (ai) such that a <= N, and for each set of (ai) generate all the (bi) such that b <= M and all the (ai+bi) are even.
Not sure that's the anywhere near efficient, but should work just fine.

Print nth Fibonacci number [upto 1000 digits] [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can one calculate nth Fibonacci number in C/C++? The Fibonacci number can contain upto 1000 digits. I can generate numbers upto 2^64 (unsigned long long). Since that is the limit of numbers, so I am guessing there has to be some other way of doing it - which I do not know of.
EDIT:
Also, it has to be done without using any external libraries.
I'll give a few hints since you haven't indicated that you've started yet.
A thousand digits is a lot. More than any built-in numeric type in C or C++ can hold.
One way to get around it is to use an arbitrary-precision math library. This will have constructs that will give you basically as many digits as you want in your numbers.
Another way is to roll your own cache-and-carry:
unsigned short int term1[1024]; // 1024 digits from 0-9
unsigned short int term2[1024]; // and another
unsigned short int sum[1024]; // the sum
addBigNumbers(&term1, &term2, &sum); // exercise for the reader
I'd expect the algorithm for addBigNumbers to go something like this:
Start at the ones digit (index 0)
Add term1[0] and term2[0]
Replace sum[0] with the right digit of term1[0] + term2[0] (which is ... ?)
Keep track of the carry (how?) and use it in the next iteration (how?)
Repeat for each digit
Now, since you're calculating a Fibonacci sequence, you'll be able to re-use these big numbers to get to the next term in the sequence. You might find that it's faster not to copy them around but to just change which ones are the terms and which one is the sum on your repeated calls to addBigNumbers.
You could try using GMP for arbitrarily large integers.

All subsets in Subset_sum_problem

I'm stuck at solving Subset_sum_problem.
Given a set of integers(S), need to compute non-empty subsets whose sum is equal to a given target(T).
Example:
Given set, S{4, 8, 10, 16, 20, 22}
Target, T = 52.
Constraints:
The number of elements N of set S is limited to 8. Hence a NP time solution is acceptable as N has a small upperbound.
Time and space complexities are not really a concern.
Output:
Possible subsets with sum exactly equal to T=52 are:
{10, 20, 22}
{4, 10, 16, 22}
The solution given in Wiki and in some other pages tries to check whether there exists such a subset or not (YES/NO).
It doesn't really help to compute all possible subsets as outlined in the above example.
The dynamic programming approach at this link gives single such subset but I need all such subsets.
One obvious approach is to compute all 2^N combinations using brute force but that would be my last resort.
I'm looking for some programmatic example(preferably C++) or algorithm which computes such subsets with illutrations/examples?
When you construct the dynamic-programming table for the subset sum problem you intialize most of it like so (taken from the Wikipedia article referenced in the question):
Q(i,s) := Q(i − 1,s) or (xi == s) or Q(i − 1,s − xi)
This sets the table element to 0 or 1.
This simple formula doesn't let you distinguish between those several cases that can give you 1.
But you can instead set the table element to a value that'd let you distinguish those cases, something like this:
Q(i,s) := {Q(i − 1,s) != 0} * 1 + {xi == s} * 2 + {Q(i − 1,s − xi) != 0} *4
Then you can traverse the table from the last element. At every element the element value will tell you whether you have zero, one or two possible paths from it and their directions. All paths will give you all combinations of numbers summing up to T. And that's at most 2N.
if N <= 8 why don't just go with 2^n solution?? it's only 256 possibilities that will be very fast
Just brute force it. If N is limited to 8, your total number of subsets is 2^8, which is only 256. They give constraints for a reason.
You can express the set inclusion as a binary string where each element is either in the set or out of the set. Then you can just increment your binary string (which can simply be represented as an integer) and then determine which elements are in the set or not using the bitwise & operator. Once you've counted up to 2^N, you know you've gone through all possible subsets.
The best way to do it is using a dynamic programming approach.However, dynamic programming just answers whether a subset sum exits or not as you mentioned in your question.
By dynamic programming, you can output all the solutions by backtracking.However, the overall time complexity to generate all the valid combinations is still 2^n.
So, any better algorithm than 2^n is close to impossible.
UPD:
From #Knoothe Comment:
You can modify horowitz-sahni's algorithm to enumerate all possible subsets.If there are M such sets whose sum equals S, then overall time complexity is in O(N * 2^(N/2) + MN)