题解:CF2252E Generational Triplets

· · 题解

根据原来的两个式子消去 b,得到 (a\oplus c)\times 2=(a+c)。

由于加法过于丑陋,考虑通过变形消去加法,很自然想到把一个 a\oplus c 减到右边去,最终得到 a\oplus c=(a\mathbin{\&}c)\times 2 。

这意味着,若 a 和 c 在二进制下第 pos 位上不同,则它们的第 pos+1 位必须同为 1,反之亦然。

因此在数位 dp 中,我们增加一个 pre 变量,记录上一位是否不同,来确定当下取值。

#include<bits/stdc++.h>
#define LL long long
using namespace std;

const LL N = 1e6 + 10 ;
const LL M = 1e9+7 ;

LL n;
LL a[100],cnt,f[100];

LL dfs(int pos,bool lead,bool limit,bool pre){
    if(pos==0) return lead&&!pre;
    if(lead&&!limit&&!pre&&f[pos]>=0) return f[pos]; 

    int up = limit ? a[pos] : 1;
    if(pre) {
        if(up==0) return 0;
        return dfs(pos-1,1,limit,0);
    }
    LL ans=0;
    for(int i=0;i<=up;++i){
        if(i==0) {
            ans+=dfs(pos-1,lead,limit&(a[pos]==0),0);
            if(lead) ans+=dfs(pos-1,lead,limit&(a[pos]==0),1);
        }
        if(i==1) ans+=dfs(pos-1,1,limit&(a[pos]==1),1);
    }

    ans%=M;
    if(lead&&!limit&&!pre) f[pos]=ans;
    return ans;
}

LL cal(LL x) {
    cnt=0;
    while(x) {
        a[++cnt]=x%2;
        x/=2;
    }
    return (M+dfs(cnt,0,1,0))%M;
}

void solve() {
    cin>>n;
    cout<<cal(n)<<endl;
}

int main(){
    for(int i=0;i<100;++i) f[i]=-1;
    int tt;
    cin>>tt;
    while(tt--) solve();
    return 0;
}