好裸的题,好坑的数据= =详见讨论版
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> using namespace std; #define MAXN 500010 #define INF 0x7fffffff struct node{ int ch[2],f,v; }tr[MAXN]; int a,tmp,x1,x2,ans; int n,root,tot; void SC(int x,int y,int z) { tr[x].ch[z]=y; tr[y].f=x; } inline bool d(int x) {return tr[tr[x].f].ch[1]==x;} void rot(int x) { int y=tr[x].f,z=tr[y].f,tt=d(x); SC(z,x,d(y));SC(y,tr[x].ch[!tt],tt);SC(x,y,!tt); //updata(y); } void splay(int x,int f) { //PD(x); while (tr[x].f!=f) { if (tr[tr[x].f].f==f) {rot(x);break;} if (d(x)==d(tr[x].f)) {rot(tr[x].f);rot(x);} else {rot(x);rot(x);} } //updata(x); } void Insert(int y) { if (!root) { root=++tot; tr[tot].v=y;tr[tot].f=0; return ; } int x=root,z; while (x) { z=x; if (y<tr[x].v) x=tr[x].ch[0]; else x=tr[x].ch[1]; } if (y<tr[z].v) tr[z].ch[0]=++tot; else tr[z].ch[1]=++tot; tr[tot].v=y;tr[tot].f=z; splay(tot,0);root=tot; } long long get(int x,int s) { int tmp=tr[x].v; while (x) { x=tr[x].ch[s]; if(x==0 || x==n+1) break; tmp=tr[x].v; } return tmp; } int main() { scanf("%d", &n); ans=0; scanf("%d", &ans); tr[0].v=tr[n+1].v=INF; Insert(ans); for (int i=2;i<=n;i++) { if (scanf("%d", &a)==EOF) a=0; Insert(a); x1=get(tr[root].ch[0],1); x2=get(tr[root].ch[1],0); tmp=INF; if (x1<INF) tmp=a-x1; if (x2<INF) tmp=min(tmp,x2-a); ans+=tmp; } printf("%d\n", ans); }