C++のpriority_queueの簡単な使い方

1727 ワード

アルゴリズムを学習する過程でよくスタックに遭遇しますが、STLのpriority_queueは(優先キュー)パッケージされたスタック構造です.
タイトルの説明
n個の整数を入力し、その中で最も小さいK個の数を見つけます.例えば4,5,1,6,2,7,3,8の8つの数字を入力すると、最小の4つの数字は1,2,3,4である.
class Solution {
public:
	vector GetLeastNumbers_Solution(vector input, int k) {
		int size = input.size();
		vector ret;
        
        if (size == 0 || k <= 0 || k > size)
            return ret;
        
		priority_queue q;
		for (int i = 0; i < size; i++) {
			if (q.size() < k)
				q.push(input[i]);
			else {
				if (input[i] < q.top()) {
					q.pop();
					q.push(input[i]);
				}
			}
		}

		while (!q.empty()) {
			ret.push_back(q.top());
			q.pop();
		}

		reverse(ret.begin(), ret.end());

		return ret;
	}
};

priority_Queueのデフォルトは、スタックの最大要素である大スタックです.小さなトップスタックを使用するには、2つのパラメータを追加する必要があります.
priority_queue, greater > q;  //    
priority_queue, less > q;     //    

サイズのトップスタックのテンプレートが提供されていますが、実際の応用では、より複雑なデータ構造を使用してスタックを構築することがよくあります.この場合、データ構造の比較方法をカスタマイズする必要があります.
方法1:
struct Node{
    int x, y;
    Node(int a = 0, int b= 0):x(a), y(b) {}
};
 
struct cmp{
    bool operator() (const Node& a, const Node& b ){
	    if (a.x == b.x) 
			return a.y > b.y;
	    return a.x > b.x; 
	}
};

priority_queue, cmp> q; 

方式2:
struct Node{
    int x, y;
    Node(int a = 0, int b= 0):x(a), y(b) {}
};

bool operator < (const Node& a, const Node& b ){
    if (a.x == b.x) 
		return a.y > b.y;
    return a.x > b.x; 
}
 
priority_queue q;