dalao们的博客:
一篇总结
线段树实现的另一种方法:二分的是值
hdu2665
线段树:
//线段树求区间第k大
//给定你一个长度为S的无序序列,每次询问其间一段[L,R],问在这一段中的第k大数是多少
//O(q*(log n)^3)
//线段树维护归并排序的过程,线段树的每一个结点是一个区间,且里面的数有序
//因为占用空间太大,只能开成vector
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
#define N 100005
struct node
{
vector<int> v;
int l,r;
}tr[4*N];
int n,q,l,r,k,T;
int a[N];
void build(int p, int l, int r)
{
tr[p].l = l;tr[p].r = r;
tr[p].v.clear();
if (l == r)
{
tr[p].v.push_back(a[l]);
return ;
}
int mid = (l + r) >> 1;
build(p<<1, l, mid);
build(p<<1|1,mid+1,r);
tr[p].v.resize(r - l + 1);//?
merge(tr[p<<1].v.begin(), tr[p<<1].v.end(), tr[p<<1|1].v.begin(), tr[p<<1|1].v.end(), tr[p].v.begin());
}
int query(int p, int l, int r, int x)
{
if (tr[p].l == l && tr[p].r == r)
return upper_bound(tr[p].v.begin(), tr[p].v.end(), x) - tr[p].v.begin();
int mid = (tr[p].l + tr[p].r) >> 1;
if (r <= mid) return query(p<<1,l,r,x);
if (l > mid) return query(p<<1|1,l,r,x);
if (l <= mid && r > mid)
return query(p<<1,l,mid, x) + query(p<<1|1,mid+1,r,x);
}
int solve(int ql, int qr, int k)
{
int l = 1, r = n, mid;
while (l < r)
{
mid = (l + r) >> 1;
//cout<<ql<<' '<<qr<<' '<<a[mid]<<' '<<query(1,ql,qr,a[mid])<<endl;
if (query(1,ql,qr,a[mid]) >= k)
r = mid;
else l = mid + 1;
}
return a[l];
}
int main()
{
scanf("%d", &T);
while(T--)
{
scanf("%d%d", &n, &q);
for (int i=1;i<=n;i++)
scanf("%d", &a[i]);
build(1,1,n);
sort(a+1,a+n+1);
while (q--)
{
scanf("%d%d%d", &l, &r, &k);
printf("%d\n", solve(l,r,k));
}
}
}
主席树:
对原理的讲解
//静态区间第k大,主席树
//hdu2665
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define N 100005
#define LOG 20//开大一点
int T,n,m,q,tot,s,t,k;
int a[N], b[N];
int root[N];
struct node
{
int ls, rs, sum;//这里没有写l,r,写在函数的参数里了
}tr[N*LOG];
int build(int l, int r)
{
int now = ++tot;
tr[now].sum = 0;
if (l < r)
{
int mid = (l + r) >> 1;
tr[now].ls = build(l, mid);
tr[now].rs = build(mid+1,r);
}
return now;
}
int insert(int pre, int l, int r, int x)
{
int now = ++tot;
tr[now] = tr[pre];
tr[now].sum++;
if (l < r)
{
int mid = (l + r) >> 1;
if (x <= mid) tr[now].ls = insert(tr[pre].ls, l, mid, x);
else tr[now].rs = insert(tr[pre].rs, mid+1, r, x);
}
return now;
}
int query(int s, int t, int l, int r, int k)
{
if (l == r) return l;
int sum = tr[tr[t].ls].sum - tr[tr[s].ls].sum;
int mid = (l + r) >> 1;
if (sum >= k)
return query(tr[s].ls, tr[t].ls, l, mid, k);
else return query(tr[s].rs, tr[t].rs, mid+1, r, k - sum);
}
int main()
{
scanf("%d", &T);
while (T--)
{
tot = 0;
scanf("%d%d", &n, &q);
for (int i=1;i<=n;i++)
{
scanf("%d", &a[i]);
b[i] = a[i];
}
sort(b+1,b+n+1);
m = unique(b+1,b+n+1) - (b+1);
root[0] = build(1,m);
for (int i=1;i<=n;i++)
{
int t = lower_bound(b+1, b+m+1, a[i]) - b;
root[i] = insert(root[i-1], 1, m, t);
}
while (q--)
{
scanf("%d%d%d", &s, &t, &k);
printf("%d\n", b[query(root[s-1], root[t], 1, m, k)]);
}
}
}