跳到正文

题解

题解 CF1245F

Kelin约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年11月3日
收录
2026年9月13日
更新
2026年11月16日
篇幅
约 2 分钟
获赞
2
题目
CF1245F

版本

  1. v1当前

题意

求[l,r][l,r]之间有多少对(x,y)(x,y)满足x+y=x⊕yx+y=x\oplus y

0≤l≤r≤1090\le l\le r\le10^9


题解

注意到l,rl,r的范围,又涉及到二进制位上运算,所以考虑按二进制来数位dpdp

设f(l,r)f(l,r)表示满足以下条件的(x,y)(x,y)有多少对

x+y=x⊕yx+y=x\oplus y

0≤x≤l0\le x\le l

0≤y≤r0\le y\le r

根据容斥可以得到Ans=f(r,r)−2f(l−1,r)+f(l−1,l−1)Ans=f(r,r)-2f(l-1,r)+f(l-1,l-1)

根据数位dpdp的基本思路

dp(p,Limx,Limy)dp(p,Lim_x,Lim_y)表示在二进制第pp位,x,yx,y是否有限制的答案

有限制表示已经选的填的数的高位是否与l,rl,r相同

如果有限制这一位填的数就不能超过l,rl,r在当前位的值

时间复杂度O(log⁡r)O(\log r)

C++
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
int L,R;ll f[33][2][2];
ll dp(int p,bool Lim_x,bool Lim_y){
	if(p==-1)return 1;
	ll&g=f[p][Lim_x][Lim_y];
	if(g!=-1)return g;
	g=0;
	int Up_x=Lim_x?(L>>p)&1:1,
		Up_y=Lim_y?(R>>p)&1:1;
	for(int i=0;i<=Up_x;++i)
		for(int j=0;j<=Up_y;++j)
			if(!(i&j))
				g+=dp(p-1,Lim_x&&i==Up_x,Lim_y&&j==Up_y);
	return g;
}
inline ll Sol(int l,int r){
	if(l<0)return 0;
	memset(f,-1,sizeof f);
	L=l,R=r;
	return dp(log2(R+1)+1,1,1);
}
int main(){
	int t,l,r;
	scanf("%d",&t);
	while(t--)
		scanf("%d%d",&l,&r),
		printf("%lld\n",Sol(r,r)-2*Sol(l-1,r)+Sol(l-1,l-1));
return 0;
}
原文