码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 4006 The kth great number (优先队列)

时间:2014-10-28 00:24:09      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   使用   sp   

优先队列头文件

#include <queue>

默认优先为从大到小优先。

自定义优先级

bubuko.com,布布扣
 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

 

本题要输出第K大的数,因为数据量大,不能每次排序,所以用优先队列来解决。

 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 (优先队列)

标签:style   blog   http   io   color   os   ar   使用   sp   

原文地址:http://www.cnblogs.com/titicia/p/4055575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!