Heap (priority queue) template

Source: Internet
Author: User

Supports up and down maintenance directions to facilitate manual maintenance of a single element in the heap (STL priority_queue and make_heap do not have this function t_t)

 

Namespace heap {
# Define p (x)> 1)
# Define L (x) <1)
# Define R (x) <1) + 1)
# Define maxn (INT) 1e5)
Template <typename T>
Struct heap {
T heap [maxn];
Int size;
Bool (* CMP) (T & A, T & B );
Void swap (T & A, T & B) {T = A; A = B; B = T ;}
Bool CMP (T & A, T & B) {return a <B ;}
Heap () {size = 0; CMP = CMP ;}
Heap (bool (* C) (T & A, T & B) {// The parameter is the pointer of the comparison function CMP.
Size = 0;
CMP = C;
}
Heap (T * begin, T * End ){
Size = end-begin;
Int I = 0;
For (; I <size; ++ I)
Heap [I + 1] = * (begin + I );
For (I = size; I; -- I)
Maintainup (I );
}
Void maintaindown (int K ){
Int M = K;
Bool CTN;
While (L (k) <size ){
CTN = 0;
If (CMP (heap [L (k)], heap [m]) M = L (k );
If (R (k) <size & CMP (heap [R (k)], heap [m]) M = R (k );
If (K! = M) Swap (M, k), cTn = 1, K = m;
If (! CTN) return;
}
}
Void maintainup (int K ){
While (P (k) & CMP (heap [K], heap [P (k)])
Swap (heap [K], heap [P (k)]), k = P (k );
}
Void insert (int K ){
Heap [++ size] = K;
Maintainup (k );
}
Void POP (int K ){
Heap [k] = heap [size --];
If (CMP (heap [P (k)], heap [k]) maintaindown (k );
Else maintainup (k );
}
};
} // Namespce heap

 

Heap (priority queue) template

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.