优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
Priority Queue (using pairs<int,int> ) Top element according to for loop iterator
我想要一个优先级队列,这样首先应该根据第一个元素(递增顺序(完成,当发生冲突时,然后基于第二个元素(递减顺序(。我想出了以下代码:
#include<bits/stdc++.h>
using namespace std;
struct Compare {
constexpr bool operator()(pair<int, int> const & a,
pair<int, int> const & b) const noexcept
{ return a.first > b.first || (a.first == b.first && a.second < b.second); }
};
int main()
{
priority_queue<pair<int,int>,
std::vector<pair<int,int> >,
Compare> Q;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int a,b;
cin>>a>>b;
Q.push(make_pair(a,b));
}
for(int i=1;i<=n;i++)
{
pair<int,int> m;
m=Q.top();
if(m.first <= i)
cout<<m.first<<" "<<m.second<<"n";
Q.pop();
}
}
问题是在 for 循环中,我希望该对在所有满足条件的对中处于顶部:
pair<ll,ll> m;
m.first <= i
例如 -
N=8, Pairs :
1 100
1 300
2 500
4 800
3 500
4 100
8 1000
2 700
然后是以下代码:
for(int i=1;i<=n;i++)
{
pair<int,int> m;
m=Q.top();
cout<<m.first<<" "<<m.second<<"n";
// Q.pop();
}
应给出以下结果:
1 300 (for i=1, it should have 2 choices : (1,100),(1,300) and select (1,300) )
2 700 (for i=2 it should have 4 choices : (1,100),(1,300),(2,500),(2,700) and select (2,700))
2 700 (for i=3 it should have 5 choices : (1,100),(1,300),(2,500),(2,700),(3,500) and select (2,700))
4 800 (for i=4,5,6,7 it should have 7 choices : (1,100),(1,300),(2,500),(2,700),(3,500),(4,100),(4,800) and select (4,800)).
8 1000 (for i=8 it should have 8 choices : (1,100),(1,300),(2,500),(2,700),(3,500),(4,100),(4,800),(8,1000) and select (8,1000)).
我希望这个例子现在已经清楚了。
问题是Priority_Queue
根据我的Compare
函数优先考虑第一个元素,因此它选择(1 300)
而不是(2 700)
来i=2,3
。
我应该怎么做才能使用 for 循环的迭代器更改优先级队列中的顶部元素?有人可以帮助我吗?
What should I do to change the top element in Priority Queue
如果更改不影响顺序,只需修改Q.top()
即可。
如果更改可能会影响订单,请Q.push()
修改后的Q.pop()
。
相关文章:
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- C++ 未初始化的本地(非全局)int 数组中的元素类型到底是什么?
- 如何在一维数组中的每个元素中都有多个int值
- 使用SWIG将numpy数组元素(int)传递给c++int
- 从 C++ 中的 int ** 数组访问元素
- unordered_map<int,int>如何处理负面元素?
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- unordered_set是否适合存储矢量<int>元素的数据结构?如果是这样,我将如何实现哈希函数?
- 是否可以交换在 c++ 中作为函数 func(say) 中的参数传递的 const 向量的两个元素,例如:vector<int>func (const vector<int>&
- 如何仅根据第二个元素对map<int,pair<int,int> >进行排序?
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 当我向 vector<int *> 添加元素时,我遇到了一些问题
- 将const int std ::数组的n元素复制到int矢量中.怎么做
- 访问矢量<矢量<int>>元素
- 如何对包含 pair<int,int> 元素的向量进行排序?排序是根据比较功能完成的
- 从矢量 c++ 添加 int 元素时出错
- 如何擦除列表中的 pair<int,int> 元素
- C++向量<int>:将 int 元素添加到向量中偶数且已经在向量中的 int 元素
- 显示列表<矢量<int>>元素