#include <iostream> #include <vector> #include <cstring> using namespace std; class Bitmap { public: Bitmap(int N) :capacity(N) //使用bitmap節省空間 { bits = new int[(capacity>>5)+1]; for(int i=0; i<=(capacity>>5); ++i) bits[i] = 0; } ~Bitmap() { delete [] bits; } void Add(int num) //添加數字num到bits中 { bits[num>>5] |= (1<<(num&0x1F)); } void Clear(int num) //清除bits中的數字num { bits[num>>5] &= ~(1<<(num&0x1F)); } string IsContain(int num) //判斷num是否在bits中 { return (( bits[num>>5] & (1<<(num&0x1F)) ) != 0) ? "YES" : "NO"; } void Sort() //對bits中的數排序,時間複雜度O(capacity) { int cnt = capacity>>5; //肯定bits中的最大索引數 while(cnt >= 0) { for(int i=31; i>=0; --i) { if( (bits[cnt] & (1<<i)) != 0) sortRes.push_back(cnt*32+i); } --cnt; } } void PrintSortRes() //打印排序後的結果 { cout<<"Sort :"; for(auto i:sortRes) cout<<i<<" "; cout<<endl; } private: int capacity; //存儲的int數據個數 int *bits; //指向存放數據的數組 vector<int> sortRes; //存放排序結果 }; int main() { Bitmap bm(100); bm.Add(4); bm.Add(37); bm.Add(99); cout<<"4 in bits? "<<bm.IsContain(4)<<endl; cout<<"37 in bits? "<<bm.IsContain(37)<<endl; cout<<"99 in bits? "<<bm.IsContain(99)<<endl; cout<<"89 in bits? "<<bm.IsContain(89)<<endl; bm.Clear(4); cout<<"4 in bits? "<<bm.IsContain(4)<<endl; vector<int> SortRes; bm.Sort(); bm.PrintSortRes(); return 0; }