priority queue with limited space: looking for a good algorithm

后端 未结 8 1654
旧巷少年郎
旧巷少年郎 2020-12-06 02:07

This is not a homework.

I\'m using a small \"priority queue\" (implemented as array at the moment) for storing last N items with smallest value. This is a b

8条回答
  •  旧巷少年郎
    2020-12-06 02:47

    Found a solution ("difference" means "priority" in the code, and maxRememberedResults is 255 (could be any (2^n - 1)):

    template  inline void swap(T& a, T& b){
        T c = a;
        a = b;
        b = c;
    }
    
    
    struct MinDifferenceArray{
        enum{maxSize = maxRememberedResults};
        int size;
        DifferenceData data[maxSize];
        void add(const DifferenceData& val){
            if (size >= maxSize){
                if(data[0].difference <= val.difference)
                    return;
    
                data[0] = val;
    
                for (int i = 0; (2*i+1) < maxSize; ){
                    int next = 2*i + 1;
                    if (data[next].difference < data[next+1].difference)
                        next++;
                    if (data[i].difference < data[next].difference)
                        swap(data[i], data[next]);
                    else
                        break;
                    i = next;
                }
            }
            else{
                data[size++] = val;
                for (int i = size - 1; i > 0;){
                    int parent = (i-1)/2;
                    if (data[parent].difference < data[i].difference){
                        swap(data[parent], data[i]);
                        i = parent;
                    }
                    else
                        break;
                }
            }
        }
    
        void clear(){
            size = 0;
        }
    
        MinDifferenceArray()
            :size(0){
        }
    };
    
    1. build max-based queue (root is largest)
    2. until it is full, fill up normally
    3. when it is full, for every new element
      1. Check if new element is smaller than root.
      2. if it is larger or equal than root, reject.
      3. otherwise, replace root with new element and perform normal heap "sift-down".

    And we get O(log(N)) insert as a worst case scenario.

    It is the same solution as the one provided by user with nickname "Moron". Thanks to everyone for replies.

    P.S. Apparently programming without sleeping enough wasn't a good idea.

提交回复
热议问题