营业额统计 Treap TYVJ1185

题目连接:http://tyvj.cpwz.cn/Problem_Show.asp?id=1185

相关知识:平衡树

题目不再赘述,比较简单的平衡树入门题,而且不用删除查询操作,只要直接要用数据结构模块就可以,在插入的时候更新答案,因为插入也是慢慢向着插入数值大小走的。

 

View Code
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<iostream>
using namespace std;
#define INF 20000000
#define MaxN 40000
struct treap
{
int x,p,l,r;
}a[MaxN];
int n,tot,ans,root,Max;

void turnright(int &t)
{
int t1=a[t].l;
a[t].l=a[t1].r;
a[t1].r=t;
t=t1;
}
void turnleft(int &t)
{
int t1=a[t].r;
a[t].r=a[t1].l;
a[t1].l=t;
t=t1;
}

void insert(int &t,int x)
{
if (t==0)
{
tot++;
t=tot;
a[t].l=0;
a[t].r=0;
a[t].x=x;
a[t].p=rand();
} else
{
if (abs(a[t].x-x)<Max) Max=abs(a[t].x-x);
if (x<a[t].x)
{
insert(a[t].l,x);
if (a[a[t].l].p < a[t].p) turnright(t);
}
else if (x>a[t].x)
{
insert(a[t].r,x);
if (a[a[t].r].p < a[t].p) turnleft(t);
}
}
}
int main()
{
int x;
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
Max=INF;
scanf("%d",&x);
insert(root,x);
if (i==1) ans+=x; else ans+=Max;
}
printf("%d\n",ans);
// system("pause");
return 0;
}

转载于:https://www.cnblogs.com/evan-oi/archive/2012/02/03/2337324.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值