文章目录

题目链接:

hdu 4417 Super Mario
牛客小白月赛9 E

hdu4417

/*主席树求[L,R]内小于等于x的个数*/
#include"bits/stdc++.h"
using namespace std;
typedef long long LL;
const int maxn=2e6+5;
int Ls[maxn],Rs[maxn],tree[maxn];//保存左右儿子
int a[maxn],b[maxn];//a是离散化后的,b是原数组 
vector<int>root;
int N,Q,n,tot;
int Build(int L,int R)
{
	int id=++tot;
	tree[id]=0;
	if(L==R)return id;
	int mid=L+R>>1;
	Ls[id]=Build(L,mid);
	Rs[id]=Build(mid+1,R);
	return id;
}
void Add(int id1,int x)
{
	int id2=++tot;//新建一个root
	root.push_back(id2);
	tree[id2]=tree[id1]+1;
	int L=1,R=n;
	while(L<R)
	{

		int mid=L+R>>1;
		if(x<=mid)
		{
			R=mid;
			Ls[id2]=++tot;
			Rs[id2]=Rs[id1];
			id2=tot;
			id1=Ls[id1];
		}
		else
		{
			L=mid+1;
			Rs[id2]=++tot;
			Ls[id2]=Ls[id1];
			id2=tot;
			id1=Rs[id1];
		}
		tree[id2]=tree[id1]+1;
	}
}
int query(int id,int L,int R,int x)
{
	if(x>=a[R])return tree[id];
	else if(x<a[L])return 0;
	int res=0;
	int mid=L+R>>1;
	if(x<=a[mid])res+=query(Ls[id],L,mid,x);//不要写成x<=mid了 
	else
	{
		res+=tree[Ls[id]];//左边的直接加上去 
		res+=query(Rs[id],mid+1,R,x);
	}
	return res;
}
int main()
{
	int T;
	cin>>T; 
	for(int Case=1;Case<=T;Case++)
	{
		cin>>N>>Q;
		tot=0;
		memset(tree,0,sizeof tree);
		root.clear();
		for(int i=1; i<=N; i++)
		{
			scanf("%d",b+i);
			a[i]=b[i];
		}
		cout<<"Case "<<Case<<":"<<endl;
		sort(a+1,a+1+N);
		n=unique(a+1,a+1+N)-(a+1);
		root.push_back(Build(1,n));
		for(int i=1; i<=N; i++)
		{
			int pos=lower_bound(a+1,a+1+n,b[i])-a;//找这个数是在离散化后的哪个位置 
			Add(root[i-1],pos);
		}
		while(Q--)
		{
			int L,R,x;
			scanf("%d%d%d",&L,&R,&x);
			L++,R++;
			cout<<query(root[R],1,n,x)-query(root[L-1],1,n,x)<<endl;
		}
	}
}