BZOJ 3401: [Usaco2009 Mar]Look Up 仰望(离线+平衡树)

刷银组刷得好开心= =

离线按权值排序,从大到小插入二叉树,查找树中比这个数大的

CODE:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 100010
struct node{
 int ch[2],x,r;
}t[maxn];
int cmp(int x,int y){
 if (t[x].x>y) return 0;
 if (t[x].x==y) return -1;
 return 1;
}
int rotate(int &x,int d){
 int u=t[x].ch[d];
 t[x].ch[d]=t[u].ch[d^1];
 t[u].ch[d^1]=x;
 x=u;
 return 0;
}
int l;
int insert(int &x,int y){
 if (x==0) {x=++l;t[x]=(node){{0,0},y,rand()};return 0;}
 int d=cmp(x,y);
 insert(t[x].ch[d],y);
 if (t[t[x].ch[d]].r>t[x].r) rotate(x,d);
 return 0;
}
int an;
int maxnum(int x,int y){
 if (x==0) return 0;
 int d=cmp(x,y);
 if (d==0) an=t[x].x;
 maxnum(t[x].ch[d],y);
 return 0;
}
int id[maxn],ans[maxn],a[maxn];
bool cmp1(int x,int y){
 if (a[x]==a[y]) return x<y;
 return a[x]>a[y];
}
int main(){
 int n;
 scanf("%d",&n);
 for (int i=1;i<=n;i++) scanf("%d",a+i);
 for (int i=1;i<=n;i++) id[i]=i;
 sort(id+1,id+1+n,cmp1);
 int root=0;
 for (int i=1;i<=n;i++) {
  an=0;
  maxnum(root,id[i]);
  ans[id[i]]=an;
  insert(root,id[i]);
 }
 for (int i=1;i<=n;i++) printf("%d\n",ans[i]);
 return 0;
}

posted @ 2014-07-10 23:17  New_Godess  阅读(164)  评论(0编辑  收藏  举报