其他分享
首页 > 其他分享> > luogu P1447_能量采集 (莫比乌斯反演)

luogu P1447_能量采集 (莫比乌斯反演)

作者:互联网

题目:

\[ans = \sum_{k=1}^{k<=n} (2*k-1)*f(k) \]

题解:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 2e5 + 5;

int pri[N], cnt;
int vis[N];
int mu[N];
int sum[N];

int read(){
    int q=0;char ch=' ';
    while(ch<'0'||ch>'9')ch=getchar();
    while(ch>='0'&&ch<='9')q=q*10+ch-'0',ch=getchar();
    return q;
}

void prime(){
    mu[1] = 1;
    for(int i = 2; i < N; ++ i){
        if(!vis[i]){
            pri[++ cnt] = i;
            mu[i] = -1;
	}
	for(int j = 1; j <= cnt && pri[j] * i < N; ++ j){
	    vis[pri[j] * i] = 1;
	    if(i % pri[j] == 0){
	        mu[pri[j] * i] = 0;
	        break;
	    }
	    mu[pri[j] * i] = -mu[i];
	}
    }
    for(int i = 1; i <= N; ++ i)
        sum[i] = sum[i - 1] + mu[i];
}

ll sol(ll n, ll m, ll k){
    n /= k, m /= k;
    ll res = 0;
    for(int i = 1, last = 1; i <= n; i = last + 1){
        last = min(n / (n / i), m / (m / i));
        res += (ll)(sum[last] - sum[i - 1]) * (n / i) * (m / i);
    }
    return res;
}

int n, m;

int main()
{
    prime();
    n = read(), m = read();
    if(n > m) swap(n, m);
    ll ans = 0;
    for(int i = 1; i <= n; ++ i){
        ans += (ll)(2* i - 1) * sol(n , m, i);
    }
    printf("%lld\n", ans);
    return 0;
}

标签:P1447,ch,gcd,int,luogu,sum,反演,ans,include
来源: https://www.cnblogs.com/A-sc/p/12628353.html