I read
for ( x = y; x > 0; x = ( y & (x-1) ) )
generates all subsets of bitmask y.
How does this iteration work? Any intuitive explanation?
source: http://codeforces.com/blog/entry/45223
see suboptimal solution section.
Intuition: Taken as a number, the bitmask y cannot have more than y subsets. So, by counting down x, you are guaranteed to hit every subset of y by bitmasking. But this creates a lot of duplicates. Think about 1101. If you count down from that and mask with y, the sequence will go. 1101, 1100, 1001, 1000, 1001, 1000, and so on. By assigning x the result of the masking operation, you skip to its last occurrence.
Proof: This leads to a simple proof by induction. Clearly, for bit strings of length 1, this procedure works. The only two subsets, 1, and 0, are emitted in that order.
Now suppose this procedure works for bitstrings of length N. Suppose Z is a bitstring of length N. If you create the bitstring 0Z, then you follow the same sequence as for Z along, since subtraction does not ever turn on higher order bits. If you create the bitstring 1Z, then the following happens: For the first 2^nnz(Z) steps, the original Z sequence is followed, with 1 prepended. And for the last 2^nnz(Z) steps, the original Z sequence is followed, with 0 prepended. Since the procedure visits every element of the smaller sequence twice, prepending 1 the first time, and 0 the second, we conclude that the procedure emits every subset of 1Z.
Taken together, we see that the procedure works for all bit strings.
The first simple fact that is used here is that if we, say, take value 7 (111 in binary) and start decrementing it repeatedly (all the way to 0) we'll pass through binary representations
111, 110, 101, 100, 011, 010, 001, 000
which in a rather obvious way to represent all possible subsets of an original 3-set.
The second fact is that in binary "to decrement x" ("to subtract 1 from x") means: to invert all bits of x starting from the least significant (rightmost) one and to the left up to (and including) the first 1 in the representation of x. "To the left" here means "in direction of increasing bit significance".
E.g.
00001000 - 1 = 00000111, i.e. we invert the `1000` tail
01010101 - 1 = 01010100, i.e. we invert just the `1` tail
10000000 - 1 = 01111111, i.e. we invert the whole thing
and so on
The decrement operation "turns off" the least significant 1 bit in the binary representation and "turns on" all zero bits to the right of it.
Now, the third fact is that in your case 1 bits of x are always a subset of 1 bits of y, since we begin with x = y and do x = (whatever) & y on every iteration.
When we do x - 1 we "turn off" (set to 0) the lowest 1 in x and "turn on" (set to 1) all 0 in x to the right from that lowest 1.
When we follow that with & y in x = (x - 1) & y we "turn off" some original bit of y in x and "turn on" all lower original bits of y in x.
At this point it should already be fairly obvious that this operation is simply a "masked decrement" of x: by doing x = (x - 1) & y we simply decrement the value of x under assumption that only bits masked by y form the value of x, while all other bits are just negligible "padding bits".
To draw the parallel to the above example with decrementing 7, the initial value of y might look as 10010100. Operation x = (x - 1) & y will see this value as a "distributed 7" of sorts (speaking informally). The x will proceed through the following values
1..1.1.., 1..1.0.., 1..0.1.., 1..0.0.., 0..1.1.., 0..1.0.., 0..0.1.., 0..0.0..
where . designates the "pading"bits" of x, which do not really participate in this "masked decrement" operation (in reality they will be 0). Note the similarity with the original example with 7.
Related
http://www.spoj.com/problems/SCALE/
I am trying to do it using recursion but getting TLE.
The tags of the problem say BINARY SEARCH.
How can one do it using binary search ?
Thanx in advance.
First thing to notice here is that if you had two weights of each size instead of one, then the problem would be quite trivial, as we we would only need to represent X in its base 3 representation and take corresponding number of weights. For, example if X=21 then we could take two times P_3 and one time P_2, and put those into another scale.
Now let's try to make something similar using the fact that we can add to both scales (including the one where X is placed):
Assume that X <= P_1+P_2+...+P_n, that would mean that X <= P_n + (P_n-1)/2 (easy to understand why). Therefore, X + P_(n-1) + P_(n-2)+...+P_1 < 2*P_n.
(*) What that means is that if we add some of the weights from 1 to n-1 to same scale as X, then the number on that scale still does
not have 2 in its n-th rightmost digit (either 0 or 1).
From now on assume that digit means a digit of a number in its base-3 representation (but it can temporarily become larger than 2 :P ). Now lets denote the total weight of first scale (where X is placed) as A=X and the other scale is B=0 and our goal is to make them equal (both A and B will change as we will make our progress) .
Let's iterate through all digits of the A from smallest to largest (leftmost). If the current digit index is i and it:
Equals to 0 then just ignore and proceed further
Equals to 1 then we place weight P_i=3^(i-1) on scale B.
Equals to 2 then we add P_i=3^(i-1) to scale A. Note that it would result in the increase of the digit (i+1).
Equals to 3 (yes this case is possible, if both current and previous digit were 2) add 1 to digit at index i+1 and go further (no weights are added to any scale).
Due to (*) obviously the procedure will run correctly (as the last digit will be equal to 1 in A), as we will choose only one weight from the set and place them correctly, and obviously the numbers A and B will be equal after the procedure is complete.
Now second case X > P_1+P_2+...+P_n. Obviously we cannot balance even if we place all weights on the second scale.
This completes the proof and shows when it is possible and the way how to place the weights to both scales to equalise them.
EDIT:
C++ code which I successfully submitted on SPOJ just now https://ideone.com/tbB7Ve
The solution to this problem is quite trivial. The idea is the same as #Yerken's answer, but expressed in a bit different way:
Only the first weight has a mass not divisible by 3. So the first weight is the only one has effect on balancing mod 3 property of the 2 scales:
If X mod 3 == 0, the first weight must not be used
If X mod 3 == 1, the first weight must be on scale B (the currently empty one)
If X mod 3 == 2, the first weight must be on scale A
Subtract both scales by weight(B) --> solution doesn't change, and now weight(A) is divisible by 3 while weight(B) == 0
Set X' = weight(A)/3 and divide every weights Pi by 3 ==> Solution doesn't change, and now it's the same problem with N' = N-1 and X' = (X+1)/3
pseudo-code:
listA <- empty
listB <- empty
for i = 1 to N {
if (X == 0) break for loop; // done!
if (X mod 3 == 1) then push i to listB;
if (X mod 3 == 2) then push i to listA;
X = (X + 1)/3; // integer division
}
hasSolution <- (X == 0)
C++ code: http://ideone.com/LXLGmE
I am grappling with this problem Codeforces 276D. Initially I used a brute force approach which obviously failed for large inputs(It started when inputs were 10000000000 20000000000). In the tutorials Fcdkbear(turtor for the contest) talks about a dp solution where a state is d[p][fl1][fr1][fl2][fr2].
Further in tutorial
We need to know, which bits we can place into binary representation of number а in p-th position. We can place 0 if the following condition is true: p-th bit of L is equal to 0, or p-th bit of L is equal to 1 and variable fl1 shows that current value of a is strictly greater then L. Similarly, we can place 1 if the following condition is true: p-th bit of R is equal to 1, or p-th bit of R is equal to 0 and variable fr1 shows that current value of a is strictly less then R. Similarly, we can obtain, which bits we can place into binary representation of number b in p-th position.
This is going over my head as when ith bit of L is 0 then how come we can place a zero in a's ith bit. If L and R both are in same bucket(2^i'th boundary like 16 and 24) we will eventually place a 0 at 4th whereas we can place a 1 if a = 20 because i-th bit of R is 0 and a > R. I am wondering what is the use of checking if a > L or not.
In essence I do not get the logic of
What states are
How do we recur
I know that might be an overkill but could someone explain it in descriptive manner as editorial is too short to explain anything.
I have already looked in here but suggested solution is different from one given in editorial. Also I know this can be solved with binary search but I am concerned with DP solution only
If I got the problem right: Start to compare the bits of l and r from left (MSB) to right(LSB). As long as these bits are equal there is no freedom of choice, the same bits must appear in a and b. the first bit differing must be 1 in r and 0 in l. they must appear also in a (0) and b(1). from here you can maximise the XOR result. simply use zeros for b an ones for a. that gives a+1==b and the xor result is a+b which is always 2^n-1.
I'm not following the logic as written above but the basic idea is to look bit by bit.
If L and R have different values in the same bit position then we have already found candidates that would maximize the xor'd value of that position (0 xor 1 = 1 xor 0 = 1). The other case to consider is whether the span of R-L is greater than the position value of that bit. If so then there must be two different values of A and B falling between L and R where that bit position has opposite values (as well as being able to generate any combinations of values in the lower bits.)
i have following quiz:
Let x be an integer larger than the odd number q. Change the value of x using the following rule
if x is even
then x / 2
else x – q
until x becomes smaller than q
If the final value of x is zero, what can you say about the original input value?
I am thinking about one thing: if x is odd or x=2*k+1 and we are subtract also odd number, we get even. Also I want to note, that unless x is power of 2, at some step dividing by 2, we get odd number. Let take q=11; x>11;let's take x=23; because x=23 is odd, we will have x=x-q x=23-11=12; now x is even so we will have x/2=6<11, so here we can't determine which value of x is about,but if x=22, then we will have x=x/2=11 x=11 is odd, so we will have x-q=0--> it means that x is multiple of q, but which one odd or even number? Let's take x=33; x is odd so x=x-11=22 it is even x=x/2=11, it is odd so x-q=0; no does it means that x is multiple of q?
Yes, it is apparently that x is multiple of q.
To test if an unsigned integer is of the form 2^n-1 we use:
x&(x+1)
What is that supposed to equal? That is,
x&(x+1) == ?
A number of the form 2^n-1 will have all of the bits up to the nth bit set. For example, 2^3-1 (7) is:
0b0111
If we add one to this, we get 8:
0b1000
Then, performing a bitwise and, we see that we get zero, because no bit is set on in both numbers. If we start with a number not of the form 2^n+1, then the result will be nonzero.
In complement to the existing answers, here is a short explanation of why numbers x that are not of the form 0b00000 (zero) or 0b0111..11 (all lowest digits set, these are all the numbers 2^n-1 for n>0) do not have the property x&(x+1) == 0.
For a number x of the form 0b????1000..00, x+1 has the same digits as x except for the least significant bit, so x & (x+1) has at least one bit set, the bit that was displayed as being set in x. By way of shorter explanation:
x 0b????1000..00
x+1 0b????1000..01
x&(x+1) 0b????10000000
For a number x of the form 0b????10111..11:
x 0b????10111..11
x+1 0b????110000000
x&(x+1) 0b????10000..00
In conclusion, if x is not either zero or written in binary with all lowest digits set, then x&(x+1) is not zero.
Zero. If X is 2^N-1, it is an unbroken string of 1's in binary. One more than that is a 1 followed by a string of zeroes same length as X, so the two numbers have no 1 bits in common in any location, so the AND of the two is zero.
Is there a way in constant working space to do arbitrary size and arbitrary base conversions. That is, to convert a sequence of n numbers in the range [1,m] to a sequence of ceiling(n*log(m)/log(p)) numbers in the range [1,p] using a 1-to-1 mapping that (preferably but not necessarily) preservers lexigraphical order and gives sequential results?
I'm particularly interested in solutions that are viable as a pipe function, e.i. are able to handle larger dataset than can be stored in RAM.
I have found a number of solutions that require "working space" proportional to the size of the input but none yet that can get away with constant "working space".
Does dropping the sequential constraint make any difference? That is: allow lexicographically sequential inputs to result in non lexicographically sequential outputs:
F(1,2,6,4,3,7,8) -> (5,6,3,2,1,3,5,2,4,3)
F(1,2,6,4,3,7,9) -> (5,6,3,2,1,3,5,2,4,5)
some thoughts:
might this work?
streamBasen -> convert(n, lcm(n,p)) -> convert(lcm(n,p), p) -> streamBasep
(where lcm is least common multiple)
I don't think it's possible in the general case. If m is a power of p (or vice-versa), or if they're both powers of a common base, you can do it, since each group of logm(p) is then independent. However, in the general case, suppose you're converting the number a1 a2 a3 ... an. The equivalent number in base p is
sum(ai * mi-1 for i in 1..n)
If we've processed the first i digits, then we have the ith partial sum. To compute the i+1'th partial sum, we need to add ai+1 * mi. In the general case, this number is going have non-zero digits in most places, so we'll need to modify all of the digits we've processed so far. In other words, we'll have to process all of the input digits before we'll know what the final output digits will be.
In the special case where m are both powers of a common base, or equivalently if logm(p) is a rational number, then mi will only have a few non-zero digits in base p near the front, so we can safely output most of the digits we've computed so far.
I think there is a way of doing radix conversion in a stream-oriented fashion in lexicographic order. However, what I've come up with isn't sufficient for actually doing it, and it has a couple of assumptions:
The length of the positional numbers are already known.
The numbers described are integers. I've not considered what happens with the maths and -ive indices.
We have a sequence of values a of length p, where each value is in the range [0,m-1]. We want a sequence of values b of length q in the range [0,n-1]. We can work out the kth digit of our output sequence b from a as follows:
bk = floor[ sum(ai * mi for i in 0 to p-1) / nk ] mod n
Lets rearrange that sum into two parts, splitting it at an arbitrary point z
bk = floor[ ( sum(ai * mi for i in z to p-1) + sum(ai * mi for i in 0 to z-1) ) / nk ] mod n
Suppose that we don't yet know the values of a between [0,z-1] and can't compute the second sum term. We're left with having to deal with ranges. But that still gives us information about bk.
The minimum value bk can be is:
bk >= floor[ sum(ai * mi for i in z to p-1) / nk ] mod n
and the maximum value bk can be is:
bk <= floor[ ( sum(ai * mi for i in z to p-1) + mz - 1 ) / nk ] mod n
We should be able to do a process like this:
Initialise z to be p. We will count down from p as we receive each character of a.
Initialise k to the index of the most significant value in b. If my brain is still working, ceil[ logn(mp) ].
Read a value of a. Decrement z.
Compute the min and max value for bk.
If the min and max are the same, output bk, and decrement k. Goto 4. (It may be possible that we already have enough values for several consecutive values of bk)
If z!=0 then we expect more values of a. Goto 3.
Hopefully, at this point we're done.
I've not considered how to efficiently compute the range values as yet, but I'm reasonably confident that computing the sum from the incoming characters of a can be done much more reasonably than storing all of a. Without doing the maths though, I won't make any hard claims about it though!
Yes, it is possible
For every I character(s) you read in, you will write out O character(s)
based on Ceiling(Length * log(In) / log(Out)).
Allocate enough space
Set x to 1
Loop over digits from end to beginning # Horner's method
Set a to x * digit
Set t to O - 1
Loop while a > 0 and t >= 0
Set a to a + out digit
Set out digit at position t to a mod to base
Set a to a / to base
Set x to x * from base
Return converted digit(s)
Thus, for base 16 to 2 (which is easy), using "192FE" we read '1' and convert it, then repeat on '9', then '2' and so on giving us '0001', '1001', '0010', '1111', and '1110'.
Note that for bases that are not common powers, such as base 17 to base 2 would mean reading 1 characters and writing 5.