zoukankan      html  css  js  c++  java
  • 用Java写一个简单的Bitmap

    /**
     * Bitmap用于标识[low, high]区间内的数的占用情况,
     * 进一步可以用来去重,用来排序等
     */
    private static class Bitmap {
        // 区间的左边界,默认为0
        private int low;
        // 区间的右边界
        private int high;
    
        // bitmap
        private byte[] bitmap;
    
        public Bitmap(int high) {
            this(0, high);
        }
    
        public Bitmap(int low, int high) {
            this.low = low;
            this.high = high;
            bitmap = new byte[(high - low) / Byte.SIZE + 1];
        }
    
        /**
         * 将x加入到bitmap中
         *
         * @param x 将要加入bitmap的数字
         * @return 如果x不在[low, high]区间中,返回false,如果将x加入bitmap成功则返回true
         */
        public boolean add(int x) {
            if (x < low || x > high) return false;
            int bitIndex = x - low;
            int blockIndex = bitIndex / Byte.SIZE;
            int offset = bitIndex % Byte.SIZE;
            byte mask = (byte) (Byte.MIN_VALUE >>> offset);
            bitmap[blockIndex] |= mask;
            return true;
        }
    
        /**
         * 将x从bitmap中删除
         *
         * @param x 将要从bitmap中删除的数字
         * @return 如果x不在[low, high]区间中,返回false,如果将x从bitmap删除成功则返回true
         */
        public boolean remove(int x) {
            if (x < low || x > high) return false;
            int bitIndex = x - low;
            int blockIndex = bitIndex / Byte.SIZE;
            int offset = bitIndex % Byte.SIZE;
            byte mask = (byte) (Byte.MIN_VALUE >>> offset);
            bitmap[blockIndex] &= ~mask;
            return true;
        }
    
        /**
         * 判断bitmap中是否存在数字x
         *
         * @param x
         * @return 如果x不在[low, high]区间中或者bitmap中不存在x,返回false,如果bitmap中存在x则返回true
         */
        public boolean contains(int x) {
            if (x < low || x > high) return false;
            int bitIndex = x - low;
            int blockIndex = bitIndex / Byte.SIZE;
            int offset = bitIndex % Byte.SIZE;
            byte mask = (byte) (Byte.MIN_VALUE >>> offset);
            return (bitmap[blockIndex] & mask) != 0;
        }
    
        public int getLow() {
            return low;
        }
    
        public int getHigh() {
            return high;
        }
    
    }
    
    -------------------------------------
    吾生也有涯,而知也无涯。
  • 相关阅读:
    UVA 10817 Headmaster's Headache(状压DP)
    UVA 11795 Mega Man's Mission(状态压缩DP)
    ZOJ3777 Problem Arrangement(状态压缩DP)
    NYOJ832 合并游戏(简单状压DP)
    UVA 1252 Twenty Questions(状压DP)
    UVA 10911 Forming Quiz Teams(状压DP)
    HDU 2196 Computer(经典树形DP)
    内连接、左外连接、右外连接、交叉连接区别 羽毛
    javaweb学习总结<转> 羽毛
    HIbernate基础 羽毛
  • 原文地址:https://www.cnblogs.com/SanjiApollo/p/13301907.html
Copyright © 2011-2022 走看看