求区间小于等于K的个数模板(只查询)

Super Mario - HDU 4417 - Virtual Judge (vjudge.net)

树状数组模板

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int N = 1e5+10;
struct node
{
	int l,r,h,id;
}p[N];
struct pl
{
	int x;
	int id;
}a[N];
bool bom(pl a,pl b)
{
	return a.x < b.x;
}
int c[N];
bool com(node a,node b)
{
	return a.h<b.h;
}
int n,m;
int lowbit(int x)
{
	return x&-x;
}
void add(int x,int k)
{
	while(x<=n)
	{
		c[x]+=k;
		x+=lowbit(x);
	}
}
int ask(int x)
{
	int ans=0;
	while(x)
	{
		ans+=c[x];
		x-=lowbit(x);
	}
	return ans;
}
int q[N];
int main()
{
	int t;
	scanf("%d",&t);
	for(int j=1;j<=t;j++)
	{
		scanf("%d %d",&n,&m);
		for(int i=1;i<=n;i++)
		{
			cin>>a[i].x;
			a[i].id = i;
			c[i]=0;
		}
		sort(a+1,a+1+n,bom);
		for(int i=1;i<=m;i++)
		{
			scanf("%d %d %d",&p[i].l,&p[i].r,&p[i].h);
			p[i].l++;
			p[i].r++; 
			p[i].id=i;
		}
		sort(p+1,p+1+m,com);
		int now=1;
		for(int i=1;i<=m;i++)
		{
			while(a[now].x<=p[i].h&&now<=n)
			{
				add(a[now].id,1);
				now++;
			}
			q[p[i].id] = ask(p[i].r) - ask(p[i].l-1);
		}
		cout<<"Case "<<j<<":"<<endl;
		for(int i=1;i<=m;i++)
		{
		       printf("%d\n",q[i]);
		}
	}
	return 0;	
} 

分块:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int N = 1e5+10;
int st[N];//每个块的初始 
int ed[N];//每个块的结尾 
int pos[N];//记录每个元素所处块的位置 
int a[N];//原数组 
int b[N];//辅助数组 
int block,t;//块的大小,块的数量 
int n,m;
void getblock(int n)
{
	block = sqrt(n);
	t = n/block;
	if(n%block) t++;
	for(int i=1;i<=t;i++)
	{
		st[i] = (i-1)*block + 1;
		ed[i] = i*block;
	}
	ed[t]=n;
	for(int i=1;i<=n;i++)
	{
		pos[i] = (i-1)/block + 1;
	} 
}
int gets(int l,int r,int h)
{
	int ans=0;
	for(int i=l;i<=r;i++)
	{
		if(a[i]<=h)
		{
			ans++;
		}
	}
	return ans;
}
int main()
{
	int T;
	scanf("%d",&T);
	for(int j=1;j<=T;j++)
	{
		scanf("%d %d",&n,&m);
		for(int i=1;i<=n;i++)
		{
			cin>>a[i];
			b[i]=a[i];
		}
		getblock(n);
		printf("Case %d:\n",j);
		for(int i=1;i<=t;i++)
		{
			sort(b+st[i],b+ed[i]+1);
		}
		for(int i=1;i<=m;i++)
		{
			int l,r,h;
			scanf("%d %d %d",&l,&r,&h);
			l++;
			r++;
			if(pos[l]==pos[r])
			{
				printf("%d\n",gets(l,r,h));
			}else
			{
				int ans=gets(l,ed[pos[l]],h)+gets(st[pos[r]],r,h);
				for(int i=pos[l]+1;i<=pos[r]-1;i++)
				{
					int L = st[i],R=ed[i];
					while(L<=R)
					{
						int mid = (L+R)>>1;
						if(b[mid]<=h) L = mid + 1;
						else R = mid - 1;
					}
					ans+=R - st[i] + 1;
				}
				printf("%d\n",ans);
			}
		} 
	}
	return 0;	
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值