题目:
http://poj.org/problem?id=2104
题意:
求区间[l,r]内第k小的元素
思路:
平方分割,效率很搓,但还是记录一下
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 100010, M = 500;
vector<int> vec[N/M+1];
int arr[N], brr[N];
int n, m;
int main()
{
while(~ scanf("%d%d", &n, &m))
{
for(int i = 1; i <= n; i++)
{
scanf("%d", &arr[i]);
brr[i] = arr[i];
vec[i/M].push_back(arr[i]);
}
//此处与挑战稍有不同,最后一部分也要排序
for(int i = 0; i <= n/M; i++) sort(vec[i].begin(), vec[i].end());
sort(brr+1, brr+1+n);
while(m--)
{
int a, b, k;
scanf("%d%d%d", &a, &b, &k);
int l = 1, r = n, res;
while(l <= r)
{
int mid = (l + r) >> 1;
int x = brr[mid];
int tl = a, tr = b, c = 0;
while(tl <= tr && tl % M != 0) if(arr[tl++] <= x) c++;
//注意是(tr+1) % M,使tr移动到某块的最后一个元素,假设最后一部分恰好是一个完整的桶,且tr是这个桶的最后一个,这时不对最后一部分排序就会出错,故上面要排序
while(tl <= tr && (tr+1) % M != 0) if(arr[tr--] <= x) c++;
while(tl < tr)
{
int d = tl / M;
c += upper_bound(vec[d].begin(), vec[d].end(), x) - vec[d].begin();
tl += M;
}
if(c >= k) res = mid, r = mid - 1;
else l = mid + 1;
}
printf("%d\n", brr[res]);
}
for(int i = 0; i < N/M; i++) vec[i].clear();
}
return 0;
}