题解:P12388 Easy Equation

· · 题解

思路

首先推式子:

\sum_{i=1}^{n}\sum_{j=1}^{n}[\texttt{popcount}(i+j)\cdot\gcd(i,j)=\max(i,j)]

设 d=\gcd(i,j),那么枚举互质的 i,j:

\sum_{d=1}^{n}\sum_{i=1}^{n/d}\sum_{j=1}^{n/d}[\texttt{popcount}((i+j)\times d)=\max(i,j)]

注意,此时是将 \texttt{popcount}(i+j)\cdot\gcd(i,j)=\max(i,j) 的左右两边都乘以了 d。

设 i > j:

\sum_{d=1}^{n}\sum_{i=1}^{n/d}\sum_{j=1}^{n/d}[\texttt{popcount}((i+j)\times d)=i]

此时我们可以枚举 d,i,j 便可以得到结果。

我们可以发现当 i>j 时循环可以遍历到 i,j,j,i 这两次,便对 f_{i\times d} 造成了 2 点贡献。同样的,当 i=j 时对 f_{i\times d} 造成了 1 点贡献。

一些优化

关于时间复杂度

可以发现 \log(10000000)\approx25,那么 \texttt{popcount}((i+j)\times d) 最大为 25,所以 i\le \texttt{popcount}((i+j)\times d),i,j\le 25,i,j 只要枚举到 25 就可以啦。

更多优化

因为 \texttt{popcount} 的时间复杂度为 \log(n),for循环时会炸掉,所以我们要预处理出 1 到 20000000 的 \texttt{popcount}。

代码

#include<bits/stdc++.h>
#define rep(i,s,t) for(int i=s;i<=t;i++)
using namespace std;
const int N=1e7+114;
int n,f[N];
bool st[30][30];
int pop[10000000<<1];
int lowbit(int x){return (x&-x);}
void init()
{
    for(int i=1;i<=2*(10000000-10);i++)pop[i]=pop[i-lowbit(i)]+1;
    rep(i,1,25)
        rep(j,1,i)
            if(__gcd(i,j)==1)st[i][j]=1;
}
int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    cin>>n;
    init();int res=0;
    rep(d,1,n)
        rep(i,1,min(25,n/d))
            rep(j,1,i)
                if(pop[i*d+j*d]==i && st[i][j])
                {
                    if(i>j)f[i*d]+=2;
                    else f[i*d]++;
                }
    rep(i,1,n)f[i]+=f[i-1],res^=f[i];
    cout<<res;
    return 0;
}
//__builtin_popcount(5)