Luo Valley P1447 [NOI2010] energy harvesting (Mobius inversion)

The meaning of problems: the problem can be converted into seeking $ \ sum_ {i = 1} ^ {n} \ sum_ {j = 1} ^ {m} (2 * gcd (i, j) -1) $

The 2 and -1 can be proposed: $ 2 * \ sum_ {i = 1} ^ {n} \ sum_ {j = 1} ^ {m} gcd (i, j) -n * m $

令Ans=$\sum_{i=1}^{n}\sum_{j=1}^{m}gcd(i,j)$

=$\sum_{d=1}^{n}d\sum_{i=1}^{n}\sum_{j=1}^{m}[gcd(i,j)==d]$

=$\sum_{d=1}^{n}d\sum_{i=1}^{\lfloor \frac{n}{d}\rfloor}\mu(i){\lfloor \frac{n}{id}\rfloor}{\lfloor \frac{m}{id}\rfloor}$

枚举id,Ans=$\sum_{T=1}^{n}{\lfloor \frac{n}{T}\rfloor}{\lfloor \frac{m}{T}\rfloor}\sum_{d|T}\mu(d)\frac{T}{d}$

This sum is just behind the Dirichlet convolution form, more coincidentally $ \ mu * id = \ varphi $.

Ans=$\sum_{T=1}^{n}{\lfloor \frac{n}{T}\rfloor}{\lfloor \frac{m}{T}\rfloor}\varphi (T)$

Output 2 * Ans-n * m to.

Pretreatment Euler function and prefix, another portion of the block is divisible.

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e5+5;
bool p[N];
int pri[N],phi[N],tot;
ll pre[N];
void init() {
    phi[1]=1;
    for(int i=2;i<N;i++) {
        if(!p[i]) pri[tot++]=i,phi[i]=i-1;
        for(int j=0;j<tot&&i*pri[j]<N;j++) {
            p[i*pri[j]]=true;
            if(i%pri[j]==0) {
                phi[i*pri[j]]=phi[i]*pri[j];
                break;
            }
            else phi[i*pri[j]]=phi[i]*phi[pri[j]];
        }
    }
    for(int i=1;i<N;i++) pre[i]=pre[i-1]+phi[i];
}
int main() {
    init();
    int n,m;
    scanf("%d%d",&n,&m);
    if(n>m) swap(n,m);
    ll ans=0;
    for(int l=1,r;l<=n;l=r+1) {
        r=min(n/(n/l),m/(m/l));
        ans+=1LL*(pre[r]-pre[l-1])*(n/l)*(m/l);
    }
    printf("%lld\n",2*ans-1LL*n*m);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/zdragon1104/p/11545442.html