hdu 4217 Data Structure?/treap
2024-10-12 19:08:51
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4217
可用线段树写,效率要高点。
这道题以前用c语言写的treap水过了。。
现在接触了c++重写一遍。。。
不带重复元素的插入删除第k大带垃圾回收,具体如下:
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
typedef long long ll;
const int MAX_N = ;
struct Node{
int v, s, fix;
Node *ch[];
inline void
set(int _fix, int _v = , int _s = , Node *p = NULL){
fix = _fix, v = _v, s = _s;
ch[] = ch[] = p;
}
inline void push_up(){
s = ch[]->s + ch[]->s + ;
}
};
int run(){
static int x = ;
x += (x << ) | ;
return x;
}
struct Treap{
Node *tail, *null, *root;
Node stack[MAX_N];
int top;
Node *store[MAX_N];
void init(){
tail = &stack[];
null = tail++;
null->set(0x7fffffff);
root = null;
top = ;
}
inline Node *newNode(int v){
Node *p = null;
if (top) p = store[--top];
else p = tail++;
p->set(run(), v, , null);
return p;
}
inline void rotate(Node* &x, int d){
Node *k = x->ch[!d];
x->ch[!d] = k->ch[d];
k->ch[d] = x;
k->s = x->s;
x->push_up();
x = k;
}
inline void insert(Node* &x, int v){
if (x == null){
x = newNode(v);
return;
} else {
int d = v > x->v;
insert(x->ch[d], v);
if (x->ch[d]->fix < x->fix) rotate(x, !d);
x->push_up();
}
}
inline void del(Node* &x, int v){
if (x == null) return;
x->s--;
if (x->v == v){
if (x->ch[] == null || x->ch[] == null){
store[top++] = x;
x = x->ch[] == null ? x->ch[] : x->ch[];
} else {
int d = x->ch[]->fix < x->ch[]->fix;
rotate(x, !d);
del(x->ch[!d], v);
}
} else {
del(x->ch[v>x->v], v);
}
if (x != null) x->push_up();
}
inline int find_kth(Node *x, int k){
int t = ;
for (;;){
t = x->ch[]->s;
if (k == t + ) break;
else if (k < t + ) x = x->ch[];
else k -= t + , x = x->ch[];
}
return x->v;
}
inline void insert(int v){
insert(root, v);
}
inline void del(int v){
del(root, v);
}
inline int find_kth(int k){
return find_kth(root, k);
}
}treap;
int main(){
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
ll ans;
int t, n, m, k, tmp, c = ;
scanf("%d", &t);
while (t--){
treap.init(), ans = ;
scanf("%d %d", &n, &m);
for (int i = ; i <= n; i++) treap.insert(i);
while (m--){
scanf("%d", &k);
ans += tmp = treap.find_kth(k);
treap.del(tmp);
}
printf("Case %d: %lld\n", c++, ans);
}
return ;
}
最新文章
- [C#] string 与 String,大 S 与小 S 之间没有什么不可言说的秘密
- gedit 没有preference项,使preference回归,并用命令行设置行号,text wrapping等
- 对 OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks 一文的理解
- git proxy
- hiho_1061_beautiful_string
- bootStrap modal无法滚动处理
- big_table练习数据表
- Hdu 1856(离散化+并查集)More is better
- jvm内存回收诡异现象
- 为什么很多第三方接口,都改成了基于http,直接传递json数据的方式来代替webservice?
- SkylineGlobe 7.0.1 &; 7.0.2版本Web开发 如何正确使用三维地图控件和工程树控件
- etcd v3 备份恢复
- participation remain wide
- H5canvas画类似心电图
- 第一册:lesson thirty nine.
- Linux 服务器中木马及木马清除
- TCP的三次握手与四次挥手理解及面试题(很全面)
- 命令行批量修改IP并ping测试
- [蓝桥杯]ALGO-91.算法训练_Anagrams问题
- 通过AI自学习,Google让Pixel 3的人像模式更优秀