HDU 5608 function [杜教筛]
HDU 5608 function
题意:数论函数满足\(N^2-3N+2=\sum_{d|N} f(d)\),求前缀和
裸题…连卷上\(1\)都告诉你了
预处理\(S(n)\)的话反演一下用枚举倍数的方法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const int N=1664512, U=1664510, mo=1e9+7, inv2 = 500000004, inv6 = 166666668;
inline int read(){
char c=getchar(); int x=0,f=1;
while(c<'0' || c>'9') {if(c=='-')f=-1; c=getchar();}
while(c>='0' && c<='9') {x=x*10+c-'0'; c=getchar();}
return x*f;
}
bool notp[N]; int p[N/10], mu[N];
void sieve(int n) {
mu[1]=1;
for(int i=2; i<=n; i++) {
if(!notp[i]) p[++p[0]] = i, mu[i] = -1;
for(int j=1; j <= p[0] && i*p[j] <= n; j++) {
notp[i*p[j]] = 1;
if(i%p[j] == 0) {mu[i*p[j]] = 0; break;}
mu[i*p[j]] = -mu[i];
}
}
}
inline void mod(int &x) {if(x>=mo) x-=mo; else if(x<0) x+=mo;}
int s[N];
void e_sieve(int n) {
for(int i=1; i<=n; i++) {
int t = (ll) i * (i-3) %mo + 2; mod(t); //printf("---i %d %d\n", i, t);
for(int j=i, k=1; j<=n; j+=i, k++) if(mu[k]) mod(s[j] += mu[k]>0 ? t : -t);
mod(s[i] += s[i-1]);
}
}
namespace ha {
const int p=1001001;
struct meow{int ne, val, r;} e[3000];
int cnt, h[p];
inline void insert(int x, int val) {
int u = x%p;
for(int i=h[u];i;i=e[i].ne) if(e[i].r == x) return;
e[++cnt] = (meow){h[u], val, x}; h[u] = cnt;
}
inline int quer(int x) {
int u = x%p;
for(int i=h[u];i;i=e[i].ne) if(e[i].r == x) return e[i].val;
return -1;
}
} using ha::insert; using ha::quer;
inline ll sum(ll n) {return n * (n+1) %mo * inv2 %mo;}
inline ll sum2(ll n) {return n * (n+1) %mo * (2*n+1) %mo *inv6 %mo;}
int dj_s(int n) { //printf("dj_s %d\n", n);
if(n <= U) return s[n];
if(quer(n) != -1) return quer(n);
int ans = (sum2(n) - 3*sum(n) + 2*n) %mo, r;
for(int i=2; i<=n; i=r+1) {
r = n/(n/i);
mod(ans -= (ll) dj_s(n/i) * (r-i+1) %mo);
}
insert(n, ans);
return ans;
}
int n;
int main() {
freopen("in", "r", stdin);
sieve(U);
e_sieve(U);
int T=read();
while(T--) {
n=read();
printf("%d\n", dj_s(n));
}
}
Copyright:http://www.cnblogs.com/candy99/