| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
为什么我写的Treap超时,哪个大牛帮我看一下,提点建议。Orz#include <iostream>
#include <cstdio>
#include <ctime>
using namespace std;
struct TreapNode
{
int value;
int size;
int fix;
TreapNode *left, *right;
inline int LeftSize()
{
return left ? left->size : 0;
}
inline int RightSize()
{
return right ? right->size : 0;
}
};
TreapNode *root = NULL;
inline void TreapLeftRotate(TreapNode *&root)
{
TreapNode *t = root->right;
root->right = t->left;
t->left = root;
root = t;
root->left->size = root->left->LeftSize() + root->left->RightSize() + 1;
root->size = root->LeftSize() + root->RightSize() + 1;
}
inline void TreapRightRotate(TreapNode *&root)
{
TreapNode *t = root->left;
root->left = t->right;
t->right = root;
root = t;
root->right->size = root->right->LeftSize() + root->right->RightSize() + 1;
root->size = root->LeftSize() + root->RightSize() + 1;
}
void TreapInsert(TreapNode *&root, int p, int value)
{
if (!root)
{
root = new TreapNode;
root->left = NULL;
root->right = NULL;
root->fix = rand();
root->size = 1;
root->value = value;
return ;
}
if (p < root->LeftSize() + 1)
{
TreapInsert(root->left, p, value);
root->size = root->LeftSize() + root->RightSize() + 1;
if (root->left->fix < root->fix)
{
TreapRightRotate(root);
}
}
else
{
TreapInsert(root->right, p - root->LeftSize() - 1, value);
root->size = root->LeftSize() + root->RightSize() + 1;
if (root->right->fix < root->fix)
{
TreapLeftRotate(root);
}
}
}
void PrintTreap(TreapNode *&root)
{
if (root->left)
{
PrintTreap(root->left);
printf(" ");
}
printf("%d", root->value);
if (root->right)
{
printf(" ");
PrintTreap(root->right);
}
delete root;
root = NULL;
}
int main()
{
freopen("POJ2828.in", "r", stdin);
freopen("POJ2828.out", "w", stdout);
int n;
while (scanf("%d", &n) != EOF)
{
srand((unsigned)time(NULL));
for (int i = 1; i <= n; i++)
{
int p, value;
scanf("%d%d", &p, &value);
if (root && p > root->size)
{
TreapInsert(root, root->size, value);
}
else
{
TreapInsert(root, p, value);
}
}
PrintTreap(root);
printf("\n");
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator