这里有详细介绍
有一道coding test的题目给你一个int n, 一串float的数,要你实时打印出当前数到这个数前n个数这n个数里最大值,没有n个数就是前面那几个数的最大值。这里就可以用cartesian tree,label记录是数的下标,p表示数值。插入操作为lg(n), 删除操作也为lg(n),总的复杂度为Nlg(n).
#include <iostream>
#include <fstream>
#include <cstdio> using namespace std; class treap_node
{
public:
int label;
float p;
treap_node *left;
treap_node *right;
treap_node()
{
left = NULL;
right = NULL;
}
}; class treap:treap_node
{
public:
treap_node *root;
treap()
{
root = NULL;
}
void treap_left_rotate(treap_node* &a)
{
treap_node *b = a->right;
a->right = b->left;
b->left = a;
a = b;
}
void treap_right_rotate(treap_node* &a)
{
treap_node *b = a->left;
a->left = b->right;
b->right = a;
a = b;
}
void treap_insert(treap_node* &a, int &label, float &p)
{
if (!a)
{
a = new treap_node;
a->label = label;
a->p = p;
}
else if (label > a->label)
{
treap_insert(a->right, label, p);
if (a->right->p > a->p)
treap_left_rotate(a);
}
else
{
treap_insert(a->left, label, p);
if (a->left->p < a->p)
treap_right_rotate(a);
}
}
void treap_delete_smallestP(treap_node* &a)
{
treap_node *p = a;
treap_node *pre = NULL;
while (p->left != NULL)
{
pre = p;
p = p->left;
}
if (pre != NULL)
{
pre->left = p->right;
}
else
a = p->right;
return;
}
void plist(treap_node *a)
{
if (a != NULL)
{
cout << "(";
plist(a->left);
cout << a->label << "/" << a->p;
plist(a->right);
cout << ")";
}
}
}; int atoi(char *s)
{
int ret = ;
while (*s != '\0') {
ret = ret * + (int)(*s - '');
s++;
}
return ret;
} int main(int argc, char **argv)
{
if (argc != ) {
cout << "invalid input" << endl;
return ;
}
//cout << argv[1] << " " << argv[2] << endl;
ifstream fin(argv[]);
if (!fin) {
cout << "unable to open the file" << endl;
return ;
}
int n = atoi(argv[]);
int count = ;
treap *p = new treap;
float s;
while (fin >> s) {
cout << s << " ";
if (count >= n)
{
p->treap_delete_smallestP(p->root);
}
p->treap_insert(p->root, count, s);
p->plist(p->root);
cout << p->root->p << endl;
count++;
}
return ;
}