ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
BinaryCounter.h File Reference

The binary counter of \( k \) bits of the amortized analysis: \( A[ 0 ] \) is the least significant bit, and add() increments the counter modulo \( 2^k \). More...

#include "ADS/Contract.h"
#include <algorithm>
#include <cstddef>
#include <vector>
#include "ADS/algorithm/impl/BinaryCounter.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Functions

std::size_t ADS::add (std::vector< int > &A)
 the increment of the counter \( A \) of \( k \) bits modulo \( 2^k \), returning the number of bits it has changed, i.e., its actual cost

Detailed description

The binary counter of \( k \) bits of the amortized analysis: \( A[ 0 ] \) is the least significant bit, and add() increments the counter modulo \( 2^k \).

One increment changes up to \( k \) bits, but \( n \) increments change at most

\[ \sum_{i=0}^{k-1} \left\lfloor \frac{n}{2^i} \right\rfloor < n \sum_{i=0}^{\infty} \frac{1}{2^i} = 2 n \]

bits, since \( A[ i ] \) changes every \( 2^i \) increments: the amortized cost of an increment is \( O( 1 ) \). The same bound comes from the potential \( \Phi \), the number of bits equal to 1: an increment that clears \( d \) bits and sets one costs \( d + 1 \) and changes \( \Phi \) by \( 1 - d \), hence its amortized cost is 2.

The contracts [see Contract.h]: the counter holds only bits, an audit, and add() changes at most \( k \) of them. The functions are defined in BinaryCounter.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, section 4.2.1, https://algoritmicamente.it/materiali/libro/capitoli/cap04.pdf
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa