简体   繁体   中英

Priority queue in c++ stl

I want to design a priority queue which in the priority of element with lower value of t[] is highest. This thing i am able to achieve.

But i also want that elements whose s[] value is zero should be at the end (regardless of their t [] value) How can i modify my code for that?

#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll t[4];
ll s[4];

struct func
{
  bool operator()(const ll lhs, const ll rhs) const
  {
    return(t[lhs] > t[rhs]);
  }
};

int main(){
t[0]=2;t[1]=3;t[2]=0;t[3]=6;
s[0]=0;s[1]=0;s[2]=1;s[3]=1;
priority_queue<ll,vector<ll>,func>pq;

pq.push(0);
pq.push(1);
pq.push(2);
pq.push(3);

// for displaying

cout<<pq.top()<<endl;
pq.pop();

cout<<pq.top()<<endl;
pq.pop();

cout<<pq.top()<<endl;
pq.pop();

cout<<pq.top()<<endl;
pq.pop();
}

Check both: if one of s s is zero, return that as lower priority, otherwise compare t s:

bool operator() (const ll lhs, const ll rhs) const {
  const bool leftIsZero = s[lhs] == 0;
  const bool rightIsZero = s[rhs] == 0;
  const bool oneIsZero = leftIsZero ^ rightIsZero;

  if (oneIsZero)
    return rightIsZero;

  return t[lhs] > t[rhs];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM