您的位置:首页 > 其它

poj 2104(主席树)

2017-05-02 20:10 302 查看
这是我的第一道主席树,感谢http://www.cnblogs.com/zyf0163/p/4749042.html的教程

#include <stdio.h>
#include <string.h>
#include <ctime>
#include <stack>
#include <string>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <map>
#include <queue>
#include <vector>
using namespace std;
#define LL long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lowbit(x) (x&-x)
#define mem(x,d) memset(x,d,sizeof(x))

const int maxn = 2e6+50;
const int INF = 0x3f3f3f3f;
struct Node
{
int l,r,lp,rp,x;
}t[maxn];
int root[maxn],tol;
int a[maxn/10],b[maxn/10];

void build(int l,int r,int& rt)
{
rt = ++tol;
t[rt].l = l;
t[rt].r = r;
t[rt].x = 0;
if(l==r) return;
int m = (l+r)>>1;
build(l,m,t[rt].lp);
build(m+1,r,t[rt].rp);
}

void update(int pre,int &rt,int pos)
{
rt = ++tol;
t[rt].l = t[pre].l;
t[rt].r = t[pre].r;
t[rt].x = t[pre].x+1;
if(t[rt].l==t[rt].r) return;
int m = (t[rt].l+t[rt].r)>>1;
if(pos<=m)
{
t[rt].rp = t[pre].rp;
update(t[pre].lp,t[rt].lp,pos);
}
else
{
t[rt].lp = t[pre].lp;
update(t[pre].rp,t[rt].rp,pos);
}
}

int query(int l,int r,int k)
{
if(t[r].l==t[r].r)
return b[t[r].l];
int tmp = t[t[r].lp].x - t[t[l].lp].x;
if(k<=tmp)
query(t[l].lp,t[r].lp,k);
else
query(t[l].rp,t[r].rp,k-tmp);
}

int main()
{
int n,q;
while(scanf("%d%d",&n,&q)!=EOF)
{
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
b[i] = a[i];
}
sort(b+1,b+1+n);
tol = 0;
build(1,n,root[0]);
for(int i=1; i<=n; i++)
{
int pos = lower_bound(b+1,b+1+n,a[i])-b;
update(root[i-1],root[i],pos);
}
// for(int i=0; i<=n; i++)
// cout<<root[i]<<endl;
while(q--)
{
int l,r,k;
scanf("%d%d%d",&l,&r,&k);
printf("%d\n",query(root[l-1],root[r],k));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: