Article Directory
1. Description of the problem
Usually in the brush theme, will encounter the largest heap, the minimum heap of problems, this time if they go to a realization is OK, but is usually not enough time, so how to deal with? At this point, you can make use of priority_queue C ++ STL.
2, concrete analysis
- It should be noted, C ++ STL default priority_queue is the biggest priority on the head of the queue, that is the biggest heap. So how to achieve the minimum heap it?
Suppose as a struct:
struct Node {
int value;
int idx;
Node (int v, int i): value(v), idx(i) {}
friend bool operator < (const struct Node &n1, const struct Node &n2) ;
};
inline bool operator < (const struct Node &n1, const struct Node &n2) {
return n1.value < n2.value;
}
priority_queue<Node> pq; // 此时pq为最大堆
If the minimum required heap, you need to achieve the following:
struct Node {
int value;
int idx;
Node (int v, int i): value(v), idx(i) {}
// friend bool operator < (const struct Node &n1, const struct Node &n2) ;
friend bool operator > (const struct Node &n1, const struct Node &n2) ;
};
inline bool operator > (const struct Node &n1, const struct Node &n2) {
return n1.value > n2.value;
}
priority_queue<Node, vector<Node>, greater<Node> > pq; // 此时greater会调用 > 方法来确认Node的顺序,此时pq是最小堆
3, otherwise
Of course, some of the smaller more hack means of. To construct such a minimum stack of type int:
priority_queue<int> pq; //
pq.push( -1 * v1) ; //
pq.push( -1 * v2) ; //
pq.push( -1 * v3) ; // 分别是插入v1, v2, v3变量的相反数,那么pq其实也就变相成为了最小堆,只是每次从pq取值后,要再次乘以-1即可
4, with the smallest stack to solve the problem
Codeforces Round #536 (Div. 2), problem: (D) Lunar New Year and a Wander
学如逆水行舟,不进则退