Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I am getting curious about this question..
How many ways can you choose a subset from the set P = {1, 2, 3, .. n}? The subset S should meet the following condition:
When you choose x (x ∈ P, x is an element of the set P) to create S, you cannot choose a * x and b * x for S.
Constraints :
1 <= n <= 1000
2 <= a < b <= n
b % a != 0 ( b is not divisible by a)
Example :
n = 3 , a = 2, b = 3
so total subsets are 5 ,i.e, {}, {1}, {2}, {3}, {2, 3}
as if in a particular subset there is 1 so 1*2 = 2 and 1*3 cant be there.
so {1,2}, {1,3} and {1,2,3} can't be there
Updated
This is related to sequence A051026 : Number of primitive subsequences of {1, 2, ..., n} in OEIS, the Online Encyclopedia of Integer Sequences.
I don't think there is any easy way to calculate the terms. Even the recursive computations are not trivial, except when n is prime where:
a(n) = 2 * a(n-1) - 1
Both the problem here and "A051026" can be thought of subproblems of a generalization of the above sequence. "A051026" is the instance with (a,b,..) = (2,3,4,5...), e.g. "all the integers >= 2".
I believe it will be easier to calculate the complimentary- that is the number of subsets of S that are not allowed. This is the number of subsets of S for each there is at least one pair (a,b) such that a divides b. After you calculate that number M' simply subtract it from the total number of subsets of S that is 2n.
Now to calculate the number of subsets of S that are not allowed you will have to apply the inclusion-exclusion principle. The solution is not very easy to implement but I don't think there is an alternative approach.
Related
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 2 years ago.
Improve this question
Given a sequence n elements, A1, A2,..., An
n ≤ 1000
Let ndigits(x) is amount of digits of x
For example:
ndigits(10000) = 5
ndigits(123) = 3
ndigits(9) = 1
It is guaranteed that sum of ndigits(Ai) ≤ 105 where 1 ≤ i ≤ n.
which means ndigits(A1) + ndigits(A2) + ... + ndigits(An) ≤ 105
Remove the least amount of digits to make the sequence non-decreasing.
Print the number of digits has been removed.
For example:
n = 4
A = [93, 31, 23, 31]
Delete the bold digits to make the sequence non-decreasing:
A = [93, 31, 23, 31] → A = [3, 3, 23, 31]
The answer is 2 (delete two digits 1 and 9)
I have attempted with naive algorithm:
For every elements from n-1 to 1, let that element Ai, remove least amount of digits to make that elements largest but smaller than the Ai+1 (***)
Use bruteforce and check the condition (***) (which take O(2sum of ndigits) time).
Is there any better algorithm ?
This can be solved using dynamic programming.
Lets first figure out how to remove digits. Use a binary number and depending on the position of 1 remove the digit in that position in the given number. An example will make things clear:
Delete-masking a number by j :
Let j = 2 - its binary representation is 10, you delete the number at the position where it is 1. For example for the number 93 delete-masking it with 2 will yield 3, delete-masking it with 3 will yield 93 itself because you cannot delete all the numbers ! delete-masking it with 1 will yield 9. I hope you get the idea.
Range of j:
The range of j will be only from 0 to 63, because the biggest number in your input is 10^5 and has only 6 digits atmost and the largest length of a binary number with 6 digits is 63.
Algorithm:
Let dp[i-1][j] represent the number of deletions that are required to make a non-decreasing subsequence when the (i-1)th number is delete-masked by a number j. If its not possible to make a non decreasing- it is something like MAX_VALUE
Update dp[i][j]:
Now to get dp[i][j] you need to compare all dp[i-1][k] with dp[i][j] and update as follows:
for j = 0 to 63:
if (length of binary representation of j <= length of the ith number ):
dp[i][j] = MAX_VALUE
for all k = 0 to 63:
if dp[i-1][k] != MAX and (ith number after delete-masking with j) >= (i-1th number after delete-masking with k) :
dp[i][j] = min(dp[i][j], dp[i-1][k] + (bitcount of j))
You get these values all the way upto arr.length-1 and then you take the minimum of all dp[arr.length-1][j] for j = 0 to 63
Base condition is :
If input array length is more than 1 :
dp[0][j] = (bitcount of j) if length of binary representation of j <= length of the number arr[0]
A working example is shown here
This question already has an answer here:
Count the total number of subsets that don't have consecutive elements
(1 answer)
Closed 4 years ago.
Given a set of consecutive numbers from 1 to n, I'm trying to find the number of subsets that do not contain consecutive numbers.
E.g., for the set [1, 2, 3], some possible subsets are [1, 2] and [1, 3]. The former would not be counted while the latter would be, since 1 and 3 are not consecutive numbers.
Here is what I have:
def f(n)
consecutives = Array(1..n)
stop = (n / 2.0).round
(1..stop).flat_map { |x|
consecutives.combination(x).select { |combo|
consecutive = false
combo.each_cons(2) do |l, r|
consecutive = l.next == r
break if consecutive
end
combo.length == 1 || !consecutive
}
}.size
end
It works, but I need it to work faster, under 12 seconds for n <= 75. How do I optimize this method so I can handle high n values no sweat?
I looked at:
Check if array is an ordered subset
How do I return a group of sequential numbers that might exist in an array?
Check if an array is subset of another array in Ruby
and some others. I can't seem to find an answer.
Suggested duplicate is Count the total number of subsets that don't have consecutive elements, although that question is slightly different as I was asking for this optimization in Ruby and I do not want the empty subset in my answer. That question would have been very helpful had I initially found that one though! But SergGr's answer is exactly what I was looking for.
Although #user3150716 idea is correct the details are wrong. Particularly you can see that for n = 3 there are 4 subsets: [1],[2],[3],[1,3] while his formula gives only 3. That is because he missed the subset [3] (i.e. the subset consisting of just [i]) and that error accumulates for larger n. Also I think it is easier to think if you start from 1 rather than n. So the correct formulas would be
f(1) = 1
f(2) = 2
f(n) = f(n-1) + f(n-2) + 1
Those formulas are easy to code using a simple loop in constant space and O(n) speed:
def f(n)
return 1 if n == 1
return 2 if n == 2
# calculate
# f(n) = f(n-1) + f(n - 2) + 1
# using simple loop
v2 = 1
v1 = 2
i = 3
while i <= n do
i += 1
v1, v2 = v1 + v2 + 1, v1
end
v1
end
You can see this online together with the original code here
This should be pretty fast for any n <= 75. For much larger n you might require some additional tricks like noticing that f(n) is actually one less than a Fibonacci number
f(n) = Fib(n+2) - 1
and there is a closed formula for Fibonacci number that theoretically can be computed faster for big n.
let number of subsets with no consecutive numbers from{i...n} be f(i), then f(i) is the sum of:
1) f(i+1) , the number of such subsets without i in them.
2) f(i+2) + 1 , the number of such subsets with i in them (hence leaving out i+1 from the subset)
So,
f(i)=f(i+1)+f(i+2)+1
f(n)=1
f(n-1)=2
f(1) will be your answer.
You can solve it using matrix exponentiation(http://zobayer.blogspot.in/2010/11/matrix-exponentiation.html) in O(logn) time.
I am stuck on a problem in which I have to print sum of 2Pi mod 1000000007 for all i where Pi is sum of numbers in ith subset of a set X.
Length of set can be upto 100000.
Value of element in the range [0,1012].
Here's the link of the Problem.
Problem Statement
I could not find any approach other than Brute-Force which gives verdict TLE.
Here's the Problem Statement
Violet, Klaus and Sunny Baudelaire were given a task by Count Olaf to keep them busy while he acquires their fortune.He has given them N numbers and asked each of them to do the following:
He asked Sunny to make all possible subsets of the set of numbers.
Then he asked Klaus to find out the sum of the number in each subsets thus formed.
Finally he asked Violet to tell him the sum of 2Pi for all i where Pi is sum of numbers in ith subset.
Since Count Olaf will be bored while listening to such a long number he's asked to give him the answer modulus 1000000007.
Can you help Baudelaires out of this predicament ?
Input Format
First line of input contains a single number N indicating the size of the set. The following line will containing N numbers that makes the set.
Output Format
Print the answer in a single line.
Input Constraints
1 ≤ N ≤ 105
0 ≤ a[i] ≤ 1012
Here's My Solution:
import itertools # importing module
#initializing the sum variable which will store final answer
t=0
#Input, number of elements in array
n=input()
#Input the array
arr=map(int,raw_input().split())
#Traverse all the possible combinations and update the sum variable 't'.
for i in xrange(len(arr)+1):
for val in itertools.combinations(arr,i):
x=sum(val)
t=(t+2**x)%1000000007
#Print final answer
print t
Here's the working algorithm which passes all testcases in time limit but I don't get the logic behind it.
from sys import stdin
mod = 10**9 + 7
n = int(stdin.readline())
ans = 1
a = map(int,stdin.readline().split())
for i in a:
j = pow(2,i,mod)
ans = (ans*(j+1))%mod
print ans
#Moderators,admins etc.
Before putting this question on hold or marking off-Topic or closed....
Please comment the reason so that I can know the reason and if possible reword it or ask on any other StackExchange Site.
I first posted it on codegolf.stackexchange.com and people(moderators) there have suggested me to post it here as it comes under algorithm category.
You can read about it here.
Programming Puzzles and Code golf
Thank You
You're given a set of numbers X, and are asked to compute sum(2^sum(x for x in A) for A a subset of X).
Let X be the set {x[0], x[1], ..., x[n]}, and S[i] be the sum of the powers of 2 of the sums of the subsets of x[0]...x[i]. That is, S[i] = sum(2^sum(x for x in A) for A a subset of x[0]...x[i])).
Subsets of x[0]...x[i+1] are either subsets of x[0]...x[i], or subsets of x[0]...x[i] with x[i+1] added.
Then:
S[i+1] = sum(2^sum(x for x in A) for A a subset of x[0]...x[i+1])
= sum(2^sum(x for x in A) for A a subset of x[0]...x[i])
+ sum(2^sum(x for x in A+{x[i+1]}) for A a subset of x[0]...x[i])
= sum(2^sum(x for x in A) for A a subset of x[0]...x[i])
+ sum(2^x[i+1] * 2^sum(x for x in A) for A a subset of x[0]...x[i])
= S[i]
+ 2^x[i+1] * S[i]
This gives us a linear-time method for computing the result:
A = [3, 3, 6, 1, 2]
m = 10**9 + 7
r = 1
for x in A:
r = (r * (1 + pow(2, x, m))) % m
print r
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 7 years ago.
Improve this question
Given 2 arrays X and Y of positive integers, x belongs to X and y belongs to Y, find pairs (x,y) such that x+y <= k
It can be done in O(nlogn + m) - where m is the size of the output.
sort array X
sort array Y
for reach element x in X:
for each y in Y in ascending order, and while y <= k-x:
yield (x,y)
Complexity of this algorithm is O(nlogn + m). However, m itself might be quadric in n - for example, if k is very large - you will need to return all pairs, and there are O(n^2) of those.
On Stackoverflow, you asked for an algorithm to pair numbers from two
arrays that satisfy a condition. a+b <= c. But you deleted your question
before I could answer. I disagree with the guys that say it is
impossible to find the pairs in O(n*log n).
It depends on the compactnes of your output. If you choose a "good"
output format i.e. specifying pairs as regions allows you to compute the
pairs by sorting the two arrays and perform a binary search over the two
arrays. But if you're forced to write out each pair, then it is obvious
that the complexity is O(n*n).
An example:
a1 = [1,6,3,5,2,4] length a1 = l1 = 6
a2 = [1,2,3,4,5,6] length a2 = l2 = 6
First sort both array in n * log n
a1 = [1,2,3,4,5,6]
a2 = [1,2,3,4,5,6]
compare value c = 5
l2/2 = 6/2 = 3
test a1[0] + a2[l2/2] = 1 + 4 =< 5 (true)
=> so it is true for all values less than a2[l2/2]
then we must test the values greater than a2[l2/2]
we take the midlle (l2/2+l2)/2 (median) of the right part of the array
and make the test
test a1[0] + a2[4] = 1 + 5 =< 5 (false)
because there no more element on left side we have not yet tested we
could take the result from our last test.
We can now say that the sum of element at index 0 of array a1 and each
element of array a2 up to the index 3 passes the test and print the
result [0,3].
Then we repeat that for the element at index 1 of array a1. And so on.
You have to sort two arrays in O(nlog(n))
Then print the two sorted arrays O(n)
Then perform the binary search n times => O(nlog(*))
The results are printed at the end of each binary search => O(n)
Now it's just a matter of interpreting the ouput correctly. ;-)
What do you think? Am I right or did I missed something? Can you use
that compact output?
Answered by Peter Paul Kiefer
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
algorithm to find a number in which product of number of 4 & 7 is maximum in given range
Let F4(X) be the number of digits 4 in the decimal representation of X, and F7(X) be the number of digits 7 in the decimal representation of X. For example,
F4(456) = 1, F4(444) = 3, F7(1) = 0, F7(747) = 2.
how the below thing can be solved?
find max of {F4(X) ∙ F7(X) : L ≤ X ≤ R}
1 ≤ L ≤ R ≤ 10^18
what is the fastest algorithm for solving this?
1.one can try brute force by finding all numbers between L and R and finding the max product but such an approach will easily time out.
Since it's an homework, I will only give you suggestions in form of questions:
How many digits are there in a number between 1 and 10^18?
Can a digit be a 7 and a 4 simultaneously?