Description

题意:给定 n个数,每给定一个数,在之前的数里找一个与当前数相差最小的数,求相差之和(第一个数为它本身)

如:5 1 2 5 4 6

Ans=5+|1-5|+|2-1|+|5-5|+|4-5|+|6-5|=5+4+1+0+1+1=12

n<=32767

Solution

平衡树入门题,每读入一个数,将当前数旋转至树根 ,在左子树中找一个最大以及右子树中最小的与根进行比较即可

Code

#include <cstdio>
#include <algorithm>
#define N 33333
#define Inf 0x7fffffff/2//会爆int
#define lc(x) ch[(x)][0]
using namespace std; int n,root,tmp,fa[N],ch[N][2],k[N],ind=1,Ans;
//k[]下标节点储存的值 inline void rotate(int p){//旋转
int q=fa[p],y=fa[q],x=(ch[q][1]==p);
ch[q][x]=ch[p][x^1];fa[ch[q][x]]=q;
ch[p][x^1]=q;fa[q]=p;
fa[p]=y;
if(y){
if(ch[y][0]==q) ch[y][0]=p;
else if(ch[y][1]==q) ch[y][1]=p;
}
} inline void splay(int x){
for(int y;y=fa[x];rotate(x))
if(fa[y]) rotate((x==lc(y))==(y==lc(fa[y]))?y:x);
root=x;
} inline void Ins(int x,int v){//插入
int y;
while(1){
y=ch[x][k[x]<v];
if(!y){//当前节点为空即储存
y=++ind;
k[y]=v;
ch[y][0]=ch[y][1]=0;
fa[y]=x;
ch[x][k[x]<v]=y;
break;
}
x=y;
}
splay(y);
} inline int Min(int x){
int t=ch[x][0];
while(ch[t][1]) t=ch[t][1];
return k[t];
} inline int Max(int x){
int t=ch[x][1];
while(ch[t][0]) t=ch[t][0];
return k[t];
} int main(){
scanf("%d%d",&n,&tmp);
k[root=1]=Ans=tmp;
Ins(root,Inf),Ins(root,-Inf);//初始化 for(int i=2;i<=n;++i){
scanf("%d",&tmp);
Ins(root,tmp);
int mi=Min(root),mx=Max(root);
Ans+=min(tmp-mi,mx-tmp);
}
printf("%d\n",Ans);
return 0;
}

最新文章

  1. block为什么用copy以及如何解决循环引用
  2. Python全栈之路8--迭代器(iter)和生成器(yield)
  3. Oracle Database常用补丁集Patch号及各版本PSU
  4. 电赛总结(四)&mdash;&mdash;波形发生芯片总结之AD9851
  5. 深入理解MVC与MVP
  6. halcon,C# 学习
  7. Java操作MongoDB
  8. ThinkPHP3.2 加载过程(一)
  9. php使用domdocument读取xml文件
  10. Linux是如何启动的
  11. Spring MVC整合DWR
  12. 框架 之 -------Spring
  13. 恢复oracle中误删除drop掉的表 闪回的方法
  14. 页面加载过渡页 loading plugin css
  15. 新 radio样式修改
  16. RT-thread嵌入式操作系统相关的问题
  17. day20_python_1124
  18. 通过adb启动app应用
  19. Shell教程 之数组
  20. NVIDIA / Intel 核芯显卡显示 + Nvidia 计算

热门文章

  1. MVC中 Remote的用法
  2. 斗鱼扩展--拦截替换js_辅助抢宝箱(六)
  3. 自己动手实现STL 03:内存基本处理工具(stl_uninitialized.h)
  4. [转]Git之忽略文件(ignore file)
  5. mstsc远程桌面全频或自定义窗口
  6. 使用adbWireless无线调试Android真机设备[转]
  7. 数据类型 -- uint32_t 类型
  8. 一个普通 iOS 码农的几个小项目相关知识点总结
  9. js 正则匹配(去掉html标签)
  10. spring-autowire机制