C++ 数据结构学习 ---- 位图

目录

1. 头文件

2. 完整代码

3.运行结果及截图


1. 头文件

#include <cstdlib>
#include <cstdio>
#include <memory.h>
#define Rank int

class Bitmap { //位图Bitmap类:以空间作为补偿,节省初始化时间(既允许插入,亦支持删除)
private:
    Rank* F; Rank N; //规模为N的向量F,记录[k]被标记的次序(即其在栈T[]中的秩)
    Rank* T; Rank top; //容量为N的栈T,记录被标记各位秩的栈,以及栈顶指针
public:
    Bitmap(Rank n = 8) //按指定(或默认)规模创建比特图(为测试暂时选用较小的默认值)
    {
        N = n; F = new Rank[N]; T = new Rank[N]; top = 0;
    } //在O(1)时间内隐式地初始化
    ~Bitmap() { delete[] F; delete[] T; } //析构时释放空间

 // 接口
    inline void reset() { top = 0; } //复位:从逻辑上切断所有校验环,O(1)
    inline void set(Rank k) { //插入:从逻辑上将B[k]置为true,O(1)
        if (!test(k)) { //忽略已带标记的位
            T[top] = k; F[k] = top++; //创建校验环
        }
    }
    inline void clear(Rank k) { //删除:从逻辑上将B[k]置为false,O(1)
        if (test(k)) //忽略不带标记的位
            if (--top) { //清除校验环,同时回收栈T的空闲单元(留意对空栈的处理)
                F[T[top]] = F[k]; T[F[k]] = T[top];
            }
    }
    inline bool test(Rank k) //从逻辑上判断B[k]是否为true,O(1)
    {
        return (-1 < F[k]) && (F[k] < top) && (k == T[F[k]]);
    }
};

2. 完整代码

#include<iostream>
#include "Bitmaps.h"
#include "Dice.h"
using namespace std;

int testBitmap(int n, int t) {
    bool* B = new bool[n]; //常规位图
    Bitmap M(n); //高效位图
    while (t-- > 0) { //重复使用位图多次
        memset(B, 0, n * sizeof(bool)); //逐位清零,O(n)
        M.reset(); //逻辑清零,O(1)
        for (int i = 0; i < 3 * n; i++) { //反复地
            int k = dice(n); //在随机位置上
            if (dice(2)) { //以50%的概率插入
                B[k] = true; M.set(k);
            }
            else { //或50%的概率清除
                B[k] = false; M.clear(k);
            }
        }
        //M.set( 29 ); //有时可卖个破绽,以反向测试本测试程序
        int k;
        for (k = 0; k < n; k++) //逐位地对比
            if (B[k] != M.test(k)) //一旦发现不合
                break; //随即退出
        if (k < n) { //并报告(assert:: k == n+1)
            cout << endl << "B[ ]:" ;//printf("\n B[]: ");
            for (int j = 0; j <= k; j++)
                B[j] ? (cout << 'x') : (cout << ' '); //  printf("%6c", B[j] ? 'x' : ' ');
            cout << endl << "M[ ]:";// printf("\n M[]: ");
            for (int j = 0; j <= k; j++) 
                M.test(j) ? (cout << 'x') : (cout << ' ');// printf("%6c", M.test(j) ? 'x' : ' ');
            cout << endl;
        }
        else
            printf("Test %4d OK\n", t);
    }
    delete[] B;
    return 0;
}

int main() {

    srand((unsigned int)time(NULL)); //设置随机种子
    int i = rand() % 50;
    testBitmap(0, i); //启动测试
    system("pause");
    return 0;
}

3.运行结果及截图

猜你喜欢

转载自blog.csdn.net/qq_58240448/article/details/128114765