优先队列 (干掉手写堆 呜呜呜~~)

优先队列

优先队列中的元素会按某种优先级依次出队列,即可实现按此优先级排序,时间复杂度和堆排序差不多

 

优先队列的头文件   #include<queue>

优先队列的定义式

1. priority_queue<int> q; 默认优先级从到大到小  

     priority_queue<int,vector<int>,greater<int> > q; 优先级从小到大

2. 除此之外我们还可以选择重载运算符  (用于结构体  ,无法直接定义)

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct pro
{
	int a;
	int b;//优先级 
};
priority_queue<pro> q;//默认大到小 
bool operator < (const pro x,const pro y)//重载小于号  变小到大 
{
	return x.b>y.b; 
} 

优先队列的操作

  1. 插入                            q.push(x);
  2. 查询队首                    a=q.top( );
  3. 删除队首                    q.pop( );
  4. 是否为空                    if( q.empty( ) )  //如果为空返回true;
  5. 返回队的大小            l=q.size( );

洛谷P3378 【模板】堆

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> > q; 
int main()
{
    int n; cin>>n; 
	int k,x;
    while(n--)
    {
        scanf("%d",&k);
        
        if(k==1) 
        {
        	scanf("%d",&x);
        	q.push(x);
        }
        
        if(k==2)
        {
            cout<<q.top()<<endl;
        }
        if(k==3)
        {
            q.pop();
        }
    }
    return 0;
}

郑重纪念一下我的手写堆 默哀0.000001s

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;

struct dui//xiao
{
    int a[1000050];
    int n;
    void up(int i)
    {
        while(i>1)
        {
            int j=i/2;
            if(a[i]<a[j])  swap(a[i],a[j]);
            else break;
            i=j;
        }
    }
     
    void down(int i)
    {
        while(i*2<=n)
        {
            int j=i*2;
            if(j+1<=n && a[j+1]<a[j])  j++;
            if(a[j]<a[i])   swap(a[i],a[j]);
            else break;
            i=j;
 		}
    }
     
    void Push(int x)
    {
        n++;
        a[n]=x;
        up(n);
    }
    
    void Pop()
    {
        a[1]=a[n];
        n--;
        down(1);
    }
    
    int  Top()
    {
        return a[1];
    }
    
    void make()
    {
        for(int i=n/2;i>=1;i--)   down(i);
    }
}q;



int main()
{
    int m;
    scanf("%d",&m);
    for(int i=1;i<=m;i++) 
    {
    	int k;
    	scanf("%d",&k);
    	if(k==1)  
    	{
    		int l;
    		scanf("%d",&l);
    		q.Push(l);
    	}
    	else if(k==2)  printf("%d\n",q.Top());
    	else if(k==3)  q.Pop();
    }
    
    
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42146446/article/details/81109073
今日推荐