HDU 4006

先上一个AC代码,用的是优先队列


#include<iostream>
#include<queue>
#include<vector>
#include<map>
#include<cstring>
using namespace std;

int main(){
	int n,k,i,num,j;
    char str[1000];
	while(cin>>n>>k){
		priority_queue<int,vector<int>,greater<int> >q;
		getchar();
		for(i=0;i<n;i++){
			gets(str);

			if(str[0]=='I'){
				num=0;
				for(j=2;j<strlen(str);j++)
					num=num*10+str[j]-'0';

				if(q.size()<k||q.empty())
					q.push(num);
				else{
					if(num>q.top()){
						q.pop();
						q.push(num);
					}
				}
			}
			else{
				cout<<q.top()<<endl;
			}
		}


	}

	return 0;
}





然后再上一个我用类似线段树的做法,这里做的时候计算了离最大数的偏移量,具体就看下面的代码了。

很可惜,RE了。

#include <cstdio>
#include <iostream>

using namespace std;

#define LEN 1000
#define MMAX 0x3f3f3f3f

typedef struct Node {
	int n;
	struct Node* lChild;
	struct Node* rChild;
	int lnum, rnum;
}Node;
Node tree[2*LEN];

int nCount;

void buildTree(Node* pRoot, int l, int r) {
	pRoot->n = MMAX;
	pRoot->lnum = pRoot->rnum = 0;
	if(l != r) {
		nCount++;
		pRoot->lChild = tree + nCount;
		nCount++;
		pRoot->rChild = tree + nCount;
		buildTree(pRoot->lChild, l, (l+r)/2);
		buildTree(pRoot->rChild, (l+r)/2+1, r);
	}
}

void insert(Node* pRoot, int num) {
	if(pRoot->n == MMAX) {
		pRoot->n = num;
		return;
	}

	if(num < pRoot->n) {
		pRoot->lnum++;
		insert(pRoot->lChild, num);
	}
	else {
		pRoot->rnum++;
		insert(pRoot->rChild, num);
	}
}

void query(Node* pRoot,int k) {
	if(pRoot->rnum+1 == k) {
		printf("%d\n", pRoot->n);
		return;
	}
	else if(pRoot->rnum+1 < k) {
		query(pRoot->lChild, k-1-pRoot->rnum);
	}
	else {
		query(pRoot->rChild, k);
	}
}

int main() {
	int n, k;
	while(scanf("%d%d", &n, &k) != EOF) {
		int i, j;
		int a;
		nCount = 0;
		buildTree(tree, 1, LEN);
		for(i = 0; i < n; i++) {
			char cmd[3];
			scanf("%s", cmd);
			if('I' == cmd[0]) {
				scanf("%d", &a);
				insert(tree, a);
			}
			else if('Q' == cmd[0]){
				query(tree, k);
			}
		}
	}
	return 0;
}




你可能感兴趣的:(HDU 4006)