POJ 1442 Black Box(treap树指针实现)
2016-05-15 21:58
399 查看
题目链接:点击打开链接
思路:本来不想用指针实现的, 但是在做动态第K小的题目时发现, 如果不用动态申请内存的方式, 数组根本开不下。
思路和静态数组模拟是一样的。
细节参见代码:
思路:本来不想用指针实现的, 但是在做动态第K小的题目时发现, 如果不用动态申请内存的方式, 数组根本开不下。
思路和静态数组模拟是一样的。
细节参见代码:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <string> #include <vector> #include <stack> #include <bitset> #include <cstdlib> #include <cmath> #include <set> #include <list> #include <deque> #include <map> #include <queue> #define Max(a,b) ((a)>(b)?(a):(b)) #define Min(a,b) ((a)<(b)?(a):(b)) using namespace std; typedef long long ll; typedef long double ld; const ld eps = 1e-9, PI = 3.1415926535897932384626433832795; const int mod = 1000000000 + 7; const int INF = 0x3f3f3f3f; // & 0x7FFFFFFF const int seed = 131; const ll INF64 = ll(1e18); const int maxn = 3e4 + 10; int T,n,m,a[maxn]; struct node { node *ch[2]; int r, v, s; int cmp(int x) const { if(x == v) return -1; return x < v ? 0 : 1; } void maintain() { s = 1; if(ch[0] != NULL) s += ch[0]->s; if(ch[1] != NULL) s += ch[1]->s; } } *g, *top, Node[maxn]; node *newnode(int x) { top -> v = x ; top -> s = 1 ; top -> r = rand () ; top -> ch[0] = top -> ch[1] = NULL ; return top ++ ; } 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 = newnode(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(); } void remove(node* &o, int x) { int d = o->cmp(x); if(d == -1) { node* u = o; if(o->ch[0] != NULL && o->ch[1] != NULL) { int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0); rotate(o, d2); remove(o->ch[d2], x); } else { if(o->ch[0] == NULL) o = o->ch[1]; else o = o->ch[0]; delete u; } } else remove(o->ch[d], x); if(o != NULL) o->maintain(); } int kth(node* o, int k) { if(o == NULL || k <= 0 || k > o->s) return 0; int s = (o->ch[0] != NULL ? o->ch[0]->s : 0); 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 v; int main() { while(~scanf("%d%d",&n,&m)) { for(int i = 1; i <= n; i++) { scanf("%d",&a[i]); } top = Node; int cnt = 1; for(int i = 1; i <= m; i++) { scanf("%d",&v); while(v >= cnt) insert(g, a[cnt++]); printf("%d\n",kth(g, i)); } } return 0; }
相关文章推荐
- 慧都独家揭晓国外十大Mac和iOS应用开发工具
- Fragment回退键addToBackStack无效的解决方法
- poj3468 A Simple Problem with Integers(成段更新)
- JAVA反编译器JD-GUI简介
- 20145206、20145325、20145326、20145311团队第一周博客
- 数据挖掘算法---KNN(附python代码)
- VS2010 ENTITY FRAMEWORK6 SQLite3 安装搭建环境
- C# + Socket断线重连
- RecycleView的分割线之私人订制
- 回到顶部按钮的制作
- ActionBar编写方法
- servlet基础
- 设计模式之观察者模式
- rsync 使用示例
- leetcode刷题,总结,记录,备忘 329
- Qt Windows下的exe执行文件中获取exe的版本号遇到的error
- MySQL的基本知识 -- 命令
- Ubuntu:unknown filesystem
- 软件工程(十一)
- 数据结构上机测试2-2:单链表操作B