Introduction To Algorithms, Cormen Et Al, Chap17 Solutions
Introduction To Algorithms, Cormen Et Al, Chap17 Solutions
Amortized Analysis
Cost
1
2
1
4
1
1
1
8
1
1
::
:
n operations cost
n
X
iD1
ci n C
lg n
X
2j D n C .2n
1/ < 3n :
j D0
2j .)
Total cost
<3.
# operations
17-2
ci D
i if i is an exact power of 2 ;
1 otherwise :
Operation
1
2
3
4
5
6
7
8
9
10
::
:
Cost
3
3
3
3
3
3
3
3
3
3
::
:
Actual cost
1
2
1
4
1
1
1
8
1
1
::
:
Credit remaining
2
3
5
4
6
8
10
5
7
9
::
:
n
X
cyi D 3n.
i D1
n
X
ci < 3n.
iD1
Then we have
n
X
iD1
cyi
n
X
actual cost 0.
iD1
Since the amortized cost of each operation is O.1/, and the amount of credit never
goes negative, the total cost of n operations is O.n/.
17-3
I NCREMENT.A/
i D0
while i < A:length and Ai == 1
Ai D 0
i D i C1
if i < A:length
Ai D 1
// Additions to books I NCREMENT start here.
if i > A:max
A:max D i
else A:max D 1
R ESET.A/
for i D 0 to A:max
Ai D 0
A:max D 1
As for the counter in the book, we assume that it costs $1 to flip a bit. In addition,
we assume it costs $1 to update A:max.
Setting and resetting of bits by I NCREMENT will work exactly as for the original
counter in the book: $1 will pay to set one bit to 1; $1 will be placed on the bit
that is set to 1 as credit; the credit on each 1 bit will pay to reset the bit during
incrementing.
In addition, well use $1 to pay to update max, and if max increases, well place an
additional $1 of credit on the new high-order 1. (If max doesnt increase, we can
just waste that $1it wont be needed.) Since R ESET manipulates bits at positions
only up to A:max, and since each bit up to there must have become the high-order 1
at some time before the high-order 1 got up to A:max, every bit seen by R ESET
has $1 of credit on it. So the zeroing of bits of A by R ESET can be completely paid
for by the credit stored on the bits. We just need $1 to pay for resetting max.
Thus charging $4 for each I NCREMENT and $1 for each R ESET is sufficient, so the
sequence of n I NCREMENT and R ESET operations takes O.n/ time.