测试,自动去重
15
1
2
3
4
5
6
-5
1
15
2
22
2
2
2
2
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 80005;
const int INF=0x7fffffff;
int ch[MAXN][2],v[MAXN],s[MAXN],p[MAXN];
int rt=0,sz=0;
inline int cmp(int a,int b){if(a==b)return -1;return a<b?0:1;}
inline void up(int o){s[o]=s[ch[o][0]]+s[ch[o][1]]+1;}
inline void rot(int &o,int d)
{int t=ch[o][d^1];ch[o][d^1]=ch[t][d];ch[t][d]=o;up(o);up(t);o=t;}
void ins(int &o,int val)
{
if(!o)
{
o=++sz;
v[o]=val;
p[o]=rand();
s[o]=1;
memset(ch[o],0,sizeof(ch[o]));
return;
}
int d=cmp(val,v[o]);
if(d==-1)return;//if there is a same variable replace it with if(d==-1)d=0;
ins(ch[o][d],val);
if(p[ch[o][d]]<p[o])rot(o,d^1);
up(o);
}
void del(int &o,int val)
{
if(!o)return;
int d=cmp(val,v[o]);
if(d==-1)
{
if(!ch[o][0])o=ch[o][1];
else if(!ch[o][1])o=ch[o][0];
else
{
int d2=p[ch[o][0]]>p[ch[o][1]] ? 1:0;
rot(o,d2);
del(ch[o][d2],val);
}
}
else del(ch[o][d],val);
up(o);
}
int find(int o,int val)
{
while(o)
{
int d=cmp(val,v[o]);
if(d==-1)return o;
o=ch[o][d];
}
return 0;
}
int kth(int o,int k)
{
if(!o || k<=0 || s[o]<k)return 0;
int d;
if(!ch[o][0])d=0;
else d=s[ch[o][0]];
if(k==d+1)return v[o];
else if(k<=d)return kth(ch[o][0],k);
else return kth(ch[o][1],k-d-1);//left child has s+1 nodes;
}
int rank(int o,int val)
{
int ret=0;
while(o)
{
printf("o=%d ret=%d\n",o,ret);
if(v[o]==val){ret+=s[ch[o][0]];break;}
else if(val<v[o])o=ch[o][0];
else{ret+=s[ch[o][0]]+1;o=ch[o][1];}
}
printf("o=%d ret=%d\n",o,ret);
return ret+1;
}
int rk(int o,int val)
{
if(!o)return 1;
if(val<=v[o])return rk(ch[o][0],val);
return rk(ch[o][1],val)+s[ch[o][0]]+1;
}
int dfs(int o)
{
if(ch[o][0])dfs(ch[o][0]);
printf("node %d val=%d\n",o,v[o]);
if(ch[o][1])dfs(ch[o][1]);
}
int lev=1;
int q[MAXN];
int head,tail;
int u;
void bfs()
{
head=tail=0;
q[tail++]=rt;
while(head<tail)
{
u=q[head++];
printf("node=%d lch=%d rch=%d val=%d s=%d p=%d\n",u,ch[u][0],ch[u][1],v[u],s[u],p[u]);
if(ch[u][0])q[tail++]=ch[u][0];
if(ch[u][1])q[tail++]=ch[u][1];
}
}
int main()
{
int n;
scanf("%d",&n);
int a;
while(n--)
{
scanf("%d",&a);
ins(rt,a);
}
bfs();
printf("\n");
dfs(rt);
a=kth(rt,9);
int b=rk(rt,22);
int c=rank(rt,22);
printf("\na=%d b=%d c=%d\n",a,b,c);
return 0;
}