標籤:優先隊列 acm c語言 編程 演算法
題目地址:POJ 1442
這題是用了兩個優先隊列,其中一個是較大優先,另一個是較小優先。讓較大優先的隊列保持k個。每次輸出較大優先隊列的隊頭。
每次取出一個數之後,都要先進行判斷,如果這個數比較大優先的隊列的隊頭要小,就讓它加入這個隊列,隊列頭移到較小優先的隊列中。然後當較大優先的數不足k個的時候,就讓較小優先的隊列的隊頭移到較大優先的隊頭中。
代碼如下;
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;int a[40000], b[40000];struct xiao{ int x; bool operator < (const xiao &a) const { return x > a.x; }};struct da{ int x; bool operator < (const da &a) const { return x<a.x; }};int main(){ int n, m, i, j, cnt, x, k; while(scanf("%d%d",&n,&m)!=EOF) { priority_queue<xiao>q1; priority_queue<da>q2; xiao f1; da f2; for(i=0; i<n; i++) { scanf("%d",&a[i]); } for(i=0; i<m; i++) { scanf("%d",&b[i]); } j=0; for(i=0; i<m; i++) { while(j<b[i]) { if(q2.empty()||a[j]>=q2.top().x) { f1.x=a[j]; q1.push(f1); } else { f1.x=q2.top().x; q1.push(f1); q2.pop(); f2.x=a[j]; q2.push(f2); } j++; } while(q2.size()<=i) { f1=q1.top(); f2.x=f1.x; q1.pop(); q2.push(f2); } printf("%d\n",q2.top()); } } return 0;}