天天看点

[杜教筛] BZOJ 3512 DZY Loves Math IV

JC大爷出的神题

送一发链接当我会做了:http://duxyz.github.io/solution/2014/04/03/DZY-Loves-Math-4/

其中有个式子不是那么显然需要理解下 实在不行就自己手写个例子

[杜教筛] BZOJ 3512 DZY Loves Math IV
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include <tr1/unordered_map>
typedef long long ll;
using namespace std;
using namespace std::tr1;

const int maxn=5000000;

int prime[1000000],num;
int vst[maxn+5],phi[maxn+5],q[maxn+5],sum[maxn+5];

const int P=1e9+7;
const int inv=500000004;

inline void Pre(){
  phi[1]=1; q[1]=1; 
  for (int i=2;i<=maxn;i++){
    if (!vst[i]) prime[++num]=i,phi[i]=i-1,q[i]=1;
    for (int j=1;j<=num && (ll)i*prime[j]<=maxn;j++){
      vst[i*prime[j]]=1;
      if (i%prime[j]==0){
	phi[i*prime[j]]=phi[i]*prime[j];
	q[i*prime[j]]=q[i]*prime[j];
	break;
      }else
	phi[i*prime[j]]=phi[i]*phi[prime[j]],q[i*prime[j]]=q[i];
    }
  }
  for (int i=1;i<=maxn;i++) (sum[i]=phi[i]+sum[i-1])%=P;
}

unordered_map<ll,int> S;

inline int Sum(ll n){
  if (n<=maxn) return sum[n];
  if (S.find(n)!=S.end()) return S[n];
  int tem=(ll)(n%P)*((n+1)%P)%P*inv%P; ll l,r;
  for (l=2;l*l<=n;l++) (tem+=P-Sum(n/l))%=P;
  for (ll t=n/l;l<=n;l=r+1,t--)
    r=n/t,(tem+=P-(ll)(r-l+1)*Sum(t)%P)%=P;
  return S[n]=tem;
}

unordered_map<ll,int> Map;

inline int Solve(int n,int m){
  if (!m) return 0;
  if (Map[(ll)n*P+m]) return Map[(ll)n*P+m];
  if (n==1) return Sum(m);
  ll tem=0;
  for (int i=1;i*i<=n;i++)
    if (n%i==0){
      (tem+=(ll)phi[n/i]*Solve(i,m/i)%P);
      if (i*i!=n) (tem+=(ll)phi[i]*Solve(n/i,m/(n/i))%P);
    }
  return Map[(ll)n*P+m]=tem%P;
}

int main(){
  int n,m;
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  scanf("%d%d",&n,&m);
  Pre();
  ll Ans=0;
  for (int i=1;i<=n;i++)
    Ans+=(ll)q[i]*Solve(i/q[i],m)%P;
  printf("%lld\n",Ans%P);
  return 0;
}