HDOJ:6534 Chika and Friendly Pairs

这道题是我在2021年9月份时Home oj上的一次比赛练习赛写到的,后面公布的时候发现是HDOJ上的原题.在HDOJ上一看,原来是2019年CCPC的原题.一开始真的是怎么写都不会.原本以为区间DP可以试试卡时长,果然不出所料直接TL了.

这道题也是我第一次接触到莫队算法.一接触就直接遇到CCPC原题,也挺无语的,但还是坚持干掉了,虽然是看了大佬的代码,哈哈!!

我看csdn上很多人都已经描述过这道题了,就是离散+树状数组+莫队.

但感觉他们在文字描述上都比较少,我这里给出一下自己的见解.

#include <bits/stdc++.h>
using namespace std;
const int maxn=27005;
struct Node
{
	int l,r,block,id;
}node[maxn];
int n,m,k,len;
int ans[maxn],q[maxn<<2],cnt=1;
int mid[maxn],pre[maxn],post[maxn],sum[maxn<<2],Ans[maxn];
int cmp(Node x,Node y)
{
	return x.block==y.block? x.r<y.r:x.block<y.block;
}
int lowbit(int x)
{
	return x&(-x);
}
int query(int x)
{
	int res=0;
	while(x)
	{
		res+=sum[x];
		x-=lowbit(x);
	}
	return res;
}
void update(int pos,int x)
{
	while(pos<=len)
	{
		sum[pos]+=x;
		pos+=lowbit(pos);
	}
}
int main()
{
	scanf("%d %d %d",&n,&m,&k);
	for(int i=1;i<=n;i++)
		scanf("%d",&ans[i]);
	for(int i=1;i<=n;i++)
	{
		q[cnt++]=ans[i]-k;
		q[cnt++]=ans[i];
		q[cnt++]=ans[i]+k;
	}
	sort(q+1,q+cnt);
	//这里的第一个sort是为了保证下面的数组去重
	len=unique(q+1,q+cnt)-q-1;
	//unique函数相当于去掉数组中重复的元素,但不是删去,而是放在数组最后面
	//所以这里的len相当记录前面不重复元素的个数
	//但unique返回的是地址,所以后面-q-1,相当于减去q[1]的地址
	int group=sqrt(n);//group记住分块 
	for(int i=1;i<=m;i++) 
	{
		scanf("%d %d",&node[i].l,&node[i].r);
		//下面那两步分块,不多说,学过莫队的都知道
		node[i].block=(node[i].l-1)/group+1; 
		node[i].id=i;
	}
	sort(node+1,node+m+1,cmp);
	for(int i=1;i<=n;i++)//这里的lower_bound函数是二分查找,自己去查吧 
	{//离散化后得到的相应序号
		mid[i]=lower_bound(q+1,q+len+1,ans[i])-q;
		pre[i]=lower_bound(q+1,q+len+1,ans[i]-k)-q;
		post[i]=lower_bound(q+1,q+len+1,ans[i]+k)-q;
	}
	//重要的是为什么要弄个mid,pre,post数组,是为了实现树状数组
	//这三个数组相当于区间,将排序后的node中,每一次莫队下去,把更新的数据进行数据变更
	//计算pre[]-1到post[]中的长度,大致我也说不太清楚.... 
	int l=1,r=0;
	int res=0;
	//莫队算法 
	for(int i=1;i<=m;i++)
	{
		while(r<node[i].r)
		{
			r++;//如果要插入元素,先查询区间和,再更新树状数组
			res+=query(post[r])-query(pre[r]-1);
			update(mid[r],1);
		}
		while(r>node[i].r)
		{
			update(mid[r],-1);//如果要删除元素,先更新树状数组,再求区间和,下面的原理一样
			res-=query(post[r])-query(pre[r]-1);
			r--;
		}
		while(l>node[i].l)
		{
			l--;
			res+=query(post[l])-query(pre[l]-1);
			update(mid[l],1);
		}
		while(l<node[i].l)
		{
			update(mid[l],-1);
			res-=query(post[l])-query(pre[l]-1);
			l++;
		}
		Ans[node[i].id]=res;
	}
	for(int i=1;i<=m;i++)
	{
		cout<<Ans[i]<<endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值