-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_2166_Bitset.cc
127 lines (115 loc) · 2.16 KB
/
Problem_2166_Bitset.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <string>
#include <vector>
using namespace std;
class Bitset
{
private:
vector<int> set;
int size;
int zeros;
int ones;
bool reverse;
public:
Bitset(int sz)
{
set = vector<int>((sz + 31) / 32);
size = sz;
zeros = sz;
ones = 0;
reverse = false;
}
// 把idx这个数字加入到位图
void fix(int idx)
{
int index = idx / 32;
int bit = idx % 32;
if (!reverse)
{
// 位图所有位的状态,维持原始含义
// 0 : 不存在
// 1 : 存在
if ((set[index] & (1 << bit)) == 0)
{
zeros--;
ones++;
set[index] |= (1 << bit);
}
}
else
{
// 位图所有位的状态,翻转了
// 0 : 存在
// 1 : 不存在
if ((set[index] & (1 << bit)) != 0)
{
zeros--;
ones++;
set[index] ^= (1 << bit);
}
}
}
// 把idx这个数字从位图中移除
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;
std::swap(zeros, ones);
}
bool all() { return ones == size; }
bool one() { return ones > 0; }
int count() { return ones; }
string toString()
{
string ans;
// i 表示总偏移
for (int i = 0, k = 0, number, status; i < size; k++)
{
number = set[k];
// j 表示数内偏移
for (int j = 0; j < 32 && i < size; j++, i++)
{
status = (number >> j) & 1;
status ^= reverse ? 1 : 0;
ans.push_back(status + '0');
}
}
return ans;
}
};
/**
* Your Bitset object will be instantiated and called as such:
* Bitset* obj = new Bitset(size);
* obj->fix(idx);
* obj->unfix(idx);
* obj->flip();
* bool param_4 = obj->all();
* bool param_5 = obj->one();
* int param_6 = obj->count();
* string param_7 = obj->toString();
*/
int main()
{
return 0;
}