KQUERY - K-query
#include <iostream>
#include <algorithm>
#define pf(i) printf("%ld\n", i)
#define sf(i) scanf("%d", &i)
#define sl(i) scanf("%ld", &i)
using namespace std;
int n, q;
long int l, r, k;
struct node
{
int l, r, p;
int v;
};
node makenode(int v,int l, int r, int p)
{
node temp;
temp.v = v; //value
temp.l = l; //left limit
temp.r = r; //right limit
temp.p = p; //position
return temp;
}
bool comp(node a, node b)
{
if(a.v == b.v)
{
return a.l > b.l;
}
return a.v > b.v;
}
void update(long int seg[], int l, int r, int index, int pos)
{
if(l == r)
{
seg[index]++;
}
else
{
int mid = (l + r) / 2;
if(pos <= mid)
{
update(seg, l, mid, 2 * index + 1, pos);
}
else
{
update(seg, mid + 1, r, 2 * index + 2, pos);
}
seg[index] = seg[2 * index + 1] + seg[2 * index + 2];
}
}
long int query(long int seg[], int l, int r, int qs, int qe, int index)
{
if(qs > r || qe < l)
return 0;
if(qs <= l && qe >= r)
return seg[index];
else
{
int mid = (l + r) / 2;
long int p1 = query(seg, l, mid, qs, qe, 2 * index + 1);
long int p2 = query(seg, mid + 1, r, qs, qe, 2 * index + 2);
return p1 + p2;
}
}
node arr[250000];
long int ans[250000];
int main()
{
sf(n);
long int seg[120000] = {0}; // max size 4 * n = 120000
int index = 0;
for(int i = 0; i < n; i++)
{
sl(k);
arr[index++] = makenode(k, 0, 0, i);
}
sf(q);
for(int i = 0; i < q; i++)
{
sl(l),sl(r), sl(k);
arr[index++] = makenode(k, l, r, i);
}
sort(arr, arr + index, comp);
for(int i = 0; i < index; i++)
{
if(arr[i].l == 0) // means it is an array element
{
update(seg, 0, n - 1, 0, arr[i].p);
}
else // it is a query
{
ans[arr[i].p] = query(seg, 0, n - 1, arr[i].l - 1, arr[i].r - 1, 0);
}
}
for(int i = 0; i < q; i++)
{
pf(ans[i]);
}
return 0;
}
Comments
Post a Comment