【POJ 1442】Black Box (treap树)
2017-02-10 20:15
267 查看
这是我自己写的第一道treap,虽然很简单,但依旧很激动。
http://blog.csdn.net/lyhvoyage/article/details/18360655
题目链接:
POJ-1442题意:
给了m个数a[1]……a[m],还有n个操作,每次输入一个u[i],求前u[i]个数中第i大的数。
题解:
1、裸treap树
#include<cstdio> #include<cstring> #include<algorithm> #include<cstdlib> using namespace std; struct node{ node *ch[2]; int r; int v; int s; node(int x){ch[0] = ch[1] = NULL; r = rand(); v = x;s = 1;} int cmp(int x) { if(x == v) return -1; else return x > v ? 1 : 0; } void maintain() { s = 1; if(ch[0] != NULL) s += ch[0]->s; if(ch[1] != NULL) s += ch[1]->s; } }; node *root; void rotate(node* &o,int d) { node* k = o->ch[d^1]; o->ch[d^1] = k->ch[d]; k->ch[d] = o; o->maintain(); k->maintain(); o = k; } void insert(node* &o,int x) { if(o == NULL) o = new node(x); else { int d = (x < o->v ? 0 : 1); insert(o->ch[d],x); if(o->ch[d]->r > o->r) rotate(o,d^1); } o->maintain(); } int kth(node* &o,int k) { if(o == NULL || k <= 0 || k > o->s) return 0; int s = (o->ch[0] == NULL ? 0 : o->ch[0]->s); if(k == s+1) return o->v; else if(k <= s) return kth(o->ch[0],k); else return kth(o->ch[1],k-s-1); } int a[30010]; int main() { int n,m,u; scanf("%d%d",&m,&n); for(int i = 1;i <= m;i++) scanf("%d",&a[i]); int len = 0; root = NULL; for(int i = 1;i <= n;i++) { scanf("%d",&u); for(;len < u;) insert(root,a[++len]); printf("%d\n",kth(root,i)); } return 0; }
2、优先队列
比较麻烦,具体是将一个优先队列分成两部分操作,大家可以参照这个人的题解:
http://blog.csdn.net/lyhvoyage/article/details/18360655
相关文章推荐
- 数据结构之Treap详解
- Treap(树堆)
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- 1611:The Suspects
- POJ1089 区间合并
- POJ 2159 Ancient Cipher
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- poj 1753 Flip Game
- poj 1328 Radar Installation