HDU 4006 the kth great number (priority queue)

Source: Internet
Author: User

Priority queue header file

# Include <queue>

The default priority is from large to small.

Custom priority

 1 struct cmpmin{                         //按从小到大          2  3 // 因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。 4     bool operator ()(int &a, int &b){ 5         return a>b;                       //所以规定小的元素的优先级大于大的元素。  6     } 7 }; 8  9 struct cmpmax{                        //按从大到小          10     bool operator ()(int &a, int &b){11         return a<b;                       12     }13 };14 15 16 //多个元素的时候 17 struct node{      18     int x, y;19     friend bool operator <(int a, int b){        //小的优先级小,所以按照x从大到小,注意默认是<来确定优先级。 20         return a.x < b.x;21     }22 }23 24 struct node{25     int x, y;26     friend bool operator <(int a, int b){        //小的优先级大,所以按照x从小到大 27         return a.x > b.x;                       28     }29 }
View code

 

This topic outputs the k-th largest number. Because the data volume is large and cannot be sorted each time, the priority queue is used to solve the problem.

 1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 #include <queue> 5 using namespace std; 6 struct cmp{ 7     bool operator ()(int &a,int &b){ 8         return a>b;//最小值优先 9     }10 };11 int n, k, val, cnt;12 char c;13 int main(){14     while(~scanf("%d%d", &n, &k)){15         cnt = 0;16         priority_queue <int, vector<int>,cmp> q;17         while(n--){18             cin>>c;19             if(c == ‘Q‘){20                 printf("%d\n", q.top());21             }22             else if(c == ‘I‘){23                 scanf("%d", &val);24                 if(cnt < k){25                     q.push(val);cnt++;26                 }27                 else{28                     if(val > q.top()){29                         q.pop();30                         q.push(val);31                     }32                 }33             }34         }35         36     }37     38     39     return 0;40 }

 

HDU 4006 the kth great number (priority queue)

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.