给定一个数d,求有多少数列,满足:1<=a1<a2…an<=n,且a1⊕a2>a2, a1⊕a2⊕a3>a3…
首先,设a1的二进制最高位为第i位,那么a2最高位>i。
像是分组背包的思想,最高位为i的元素为一组,因为最高位为i,那么该组只能选最多一个。
dp[i]为以最高位元素为i结尾的数量,那么dp[i] = (1 + dp[ 0 ~ i-1])*(2^i)。
那么,设d的最高位元素为t,ans += dp[i] (0<=i<t),然后特殊处理最高位元素为t的情况 (1 + dp[ 0 ~ i-1] ) * ( d-(1<<t)+1)
- 代码
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<list>
#include<stack>
#include<queue>
#include<vector>
#define cl (k<<1)
#define cr (k<<1|1)
#define Mid ((a[k].l+a[k].r)>>1)
#define mem(a,x) memset(a,x,sizeof(a))
using namespace std;
#define bug printf("???\n")
typedef long long LL;
const int Inf=0x3f3f3f3f;
const double eps=1e-8;
const int maxn=50;
LL dp[maxn];
LL num[maxn];
int main()
{
int T;
cin>>T;
while(T--){
LL d,m;
cin>>d>>m;
dp[0] = 1%m;
num[0] = 1;
for(LL i=1; i<=32; i++){
dp[i] = 1;
num[i] = ((LL)1<<i);
for(int k=0; k<i; k++){
dp[i] = (dp[i] + dp[k])%m;
}
dp[i] = dp[i]*num[i] %m;
}
// for(int i=0; i<3; i++) cout<<"("<<dp[i]<<")"<<endl;
LL id=upper_bound(num, num+33, d)-num - 1;
LL ans=0, tmp=1;
for(int i=0; i<id; i++){
ans = (ans+dp[i])%m;
tmp = (tmp+dp[i])%m;
}
ans = (ans + tmp*(d-num[id]+1) )%m;
cout<<ans<<endl;
}
}