您的位置:首页 > 其它

POJ 1442 堆的应用 优先队列

2016-02-23 19:19 393 查看
点击打开链接

i 数列序号

1 ADD(3) 0 3

2 GET 1 3 3

3 ADD(1) 1 1, 3

4 GET 2 1, 3 3

5 ADD(-4) 2 -4, 1, 3

6 ADD(2) 2 -4, 1, 2, 3

7 ADD(8) 2 -4, 1, 2, 3, 8

8 ADD(-1000) 2 -1000, -4, 1, 2, 3, 8

9 GET 3 -1000, -4, 1, 2, 3, 8 1

10 GET 4 -1000, -4, 1, 2, 3, 8 2

11 ADD(2) 4 -1000, -4, 1, 2, 2, 3, 8

题意:

让你依次插入n个数,使得到的序列有序 a[];

然后输入m个数,b[i]

让你 求第 b[i]次插入之后输出序列中第i小的值

思路:

利用 大顶堆与小顶堆;

往大顶堆中存储前k小的数

堆顶就是 第k小的数(即1->k 最大数)

往小顶堆中存第k+1 小到最大的数

堆顶就是第k+1小的数((K+1->i)最小数)

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int bigheap[30010],a[30010],b[30010];
int smheap[30010];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
scanf("%d",&a[i]);
b[0]=0;
for(int i=1; i<=m; i++)
scanf("%d",&b[i]);
int small=0;
for(int c=1; c<=m; c++)
{
for(int i=b[c-1]+1; i<=b[c]; i++)
{
smheap[small]=a[i];
small++;
push_heap(smheap,smheap+small,greater<int>());
if(bigheap[0]>smheap[0]&&c-1!=0)
{
int cc=bigheap[0];
pop_heap(bigheap,bigheap+c);
bigheap[c-1]=smheap[0];
push_heap(bigheap,bigheap+c);
pop_heap(smheap,smheap+small,greater<int>());
smheap[small-1]=cc;
push_heap(smheap,smheap+small,greater<int>());
}
}
printf("%d\n",smheap[0]);
bigheap[c-1]=smheap[0];
push_heap(bigheap,bigheap+c);
pop_heap(smheap,smheap+small,greater<int>());
small--;
}
return 0;
}


优先队列就是利用了堆的原理

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int a[31000],b[31000];
int main()
{
priority_queue<int,vector<int>,less<int> >big;   ///大顶堆
priority_queue<int,vector<int>,greater<int> >small;///小顶堆
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
b[0]=0;
for(int j=1;j<=m;j++)
scanf("%d",&b[j]);
for(int c=1;c<=m;c++)
{
for(int i=b[c-1]+1;i<=b[c];i++)
{
small.push(a[i]);
if(!big.empty()&&big.top()>small.top())
{
int cc=big.top();
big.pop();
big.push(small.top());
small.pop();
small.push(cc);
}
}
big.push(small.top());
small.pop();
printf("%d\n",big.top());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: