Thursday, January 31, 2013

a very good example of iterative refinement of brute-force solution

string search: given two strings s and t, find all occurrences of s in t. since s can occur at any offset in t. the brutal force solution is to test for a match at every offset.

1. accelerate:
matching backwards.

2. a partial match does not result in full match implies other offsets which cannot lead to full matches.

data structure introduction:

min_heap


Use make_heap() and friends, defined in <algorithm>, or use priority_queue, defined in<queue>. The priority_queue uses make_heap and friends underneath.
#include <queue> // functional,iostream,ctime,cstdlib
using namespace std;

int main(int argc, char* argv[])
{
    srand(time(0));
    priority_queue<int,vector<int>,greater<int> > q;
    for( int i = 0; i != 10; ++i ) q.push(rand()%10);
    cout << "Min-heap, popped one by one: ";
    while( ! q.empty() ) {
        cout << q.top() << ' ';  // 0 3 3 3 4 5 5 6 8 9
        q.pop();
    }
    cout << endl;
    return 0;
}


Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels, whereas BST guarantees order (from "left" to "right"). If you want sorted elements, go with BST.

No comments:

Post a Comment