标签:
有一个点答案错误,求大神指教
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
struct shu
{
int zhi,dui,l,r,sum1;
}a[32768];
int n,sum,root,size,ans;
void qian(int a1,int a2)
{
if(a1==0)
return;
if(a[a1].zhi==a2)
{
ans=a2;
return;
}
if(a[a1].zhi<a2)
{
ans=a[a1].zhi;
qian(a[a1].r,a2);
}
else
qian(a[a1].l,a2);
return;
}
void hou(int a1,int a2)
{
if(a1==0)
return;
if(a[a1].zhi==a2)
{
ans=a2;
return;
}
if(a[a1].zhi>a2)
{
ans=a[a1].zhi;
hou(a[a1].l,a2);
}
else
hou(a[a1].r,a2);
return;
}
void zuo(int &a1)
{
int t=a[a1].r;
a[a1].r=a[t].l;
a[t].l=a1;
a1=t;
return;
}
void you(int &a1)
{
int t=a[a1].l;
a[a1].l=a[t].r;
a[t].r=a1;
a1=t;
return;
}
void jia(int &a1,int a2)
{
if(a1==0)
{
size++;
a1=size;
a[a1].zhi=a2;
a[a1].sum1=1;
a[a1].dui=rand();
return;
}
if(a[a1].zhi==a2)
a[a1].sum1++;
else
if(a[a1].zhi<a2)
{
jia(a[a1].r,a2);
if(a[a[a1].r].dui<a[a1].dui)
zuo(a1);
}
else
{
jia(a[a1].l,a2);
if(a[a[a1].l].dui<a[a1].dui)
you(a1);
}
return;
}
int main()
{
scanf("%d",&n);
scanf("%d",&sum);
jia(root,sum);
for(int i=1;i<n;i++)
{
int a1;
scanf("%d",&a1);
int minn=0X7fffff;
ans=-1;
qian(root,a1);
if(ans>-1)
minn=a1-ans;
ans=-1;
hou(root,a1);
if(ans>-1)
minn=min(ans-a1,minn);
sum+=minn;
jia(root,a1);
}
printf("%d\n",sum);
return 0;
}
标签:
原文地址:http://www.cnblogs.com/xydddd/p/5130859.html