class Bitset {
int* set;
int size;
int zeros;
int ones;
bool reverse;
public:
Bitset(int size) {
set = new int[(size+31)/32]();
this->size = size;
zeros = size;
ones = 0;
reverse = false;
}
~Bitset() {
delete[] set;
}
void fix(int idx) {
int index = idx / 32;
int bit = idx % 32;
if(!reverse) {
if((set[index] & (1 << bit)) == 0) {
ones++;
zeros--;
set[index] |= (1 << bit);
}
} else {
if((set[index] & (1 << bit)) != 0) {
ones++;
zeros--;
set[index] ^= (1 << bit);
}
}
}
void unfix(int idx) {
int index = idx / 32;
int bit = idx % 32;
if(!reverse) {
if((set[index] & (1 << bit)) != 0) {
ones--;
zeros++;
set[index] ^= (1 << bit);
}
} else {
if((set[index] & (1<<bit)) == 0) {
ones--;
zeros++;
set[index] |= (1 << bit);
}
}
}
void flip() {
reverse = !reverse;
int temp = ones;
ones = zeros;
zeros = temp;
}
bool all() {
return ones == size;
}
bool one() {
return ones > 0;
}
int count() {
return ones;
}
string toString() {
string s = "";
for(int i = 0, k = 0, num, sta; i < size; k++) {
num = set[k];
for(int j = 0; j < 32 && i < size; i++, j++) {
sta = (num >> j) & 1;
s += (reverse ? (sta ? "0" : "1") : (sta ? "1" : "0"));
}
}
return s;
}
};
2166.设计位集
于 2024-08-04 22:17:49 首次发布