bzoj 3202 [Sdoi2013]项链——容斥+置换+推式子

题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3202

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int N=1e7+5,mod=1e9+7,base=1e5;
ll M=(ll)(1e9+7)*(ll)(1e9+7);//(ll)!!!!!
int a,T,pri[N],cnt;ll n,t,u[N],ans,p[65],q[65],tot,tmd;
bool vis[N],fx;
void upd(ll &x,ll md){x>=md?x-=md:0;x<0?x+=md:0;}
/*ll mul(ll a,ll b,ll md)
{ll ret=0;while(b){if(b&1ll)ret+=a,upd(ret,md);a+=a;upd(a,md);b>>=1ll;}return ret;}*/
/*ll mul(ll a,ll b,ll md)//slow and WA?
{
  ll bs=(md==M?mod:base);
  ll A=a/bs,B=a%bs,C=b/bs,D=b%bs;
  ll ret=A*C%md*bs%md*bs%md;
  ret=(ret+A*D%md*bs)%md;
  ret=(ret+B*C%md*bs)%md;
  ret=(ret+B*D)%md;
  return ret;
  }
*/
ll mul(ll a,ll b,ll md)
{
  return (a*b-(ll)( ((long double)a*b+0.5)/(long double)md )*md+md)%md;
}
ll pw(ll x,ll k,ll md)
{x%=md;k%=(md-1);ll ret=1;while(k){if(k&1)ret=mul(ret,x,md);x=mul(x,x,md);k>>=1;}return ret;}
void calc(ll md)
{
  ll g2=0,g3=0;
  for(int i=1,j,d;i<=a;i=j+1)
    {
      d=a/i; j=a/d; ll k=u[j]-u[i-1];upd(k,md);
      ll tmp=mul(mul(d,d,md),k,md);
      g2=g2+tmp; upd(g2,md);
      tmp=mul(tmp,d,md);
      g3=g3+tmp; upd(g3,md);
    }
  t=(g3+3*g2+2)%md;
  t=mul(t,pw(6,fx?M-mod-1:mod-2,md),md);//phi(M)=mod*(mod-1)
}
void init()
{
  memset(vis,0,sizeof vis); cnt=0;
  u[1]=1;  ll d;
  for(int i=2;i<=a;i++)
    {
      if(!vis[i])u[i]=-1,pri[++cnt]=i;
      for(int j=1;j<=cnt&&(d=(ll)i*pri[j])<=a;j++)
    {
      vis[d]=1;u[d]=-u[i];
      if(i%pri[j]==0){u[d]=0;break;}
    }
    }
  for(int i=2;i<=a;i++)u[i]+=u[i-1],upd(u[i],tmd);
  calc(tmd);
}
ll F(ll x,ll md)
{
  ll ret=0;
  if(x&1ll)ret=1-t; else ret=t-1;
  upd(ret,md);
  ret+=pw(t-1,x,md); upd(ret,md);
  return ret;
}
ll Phi(ll x,ll md)
{
  ll ret=x,yx=x;
  for(ll d=2;d*d<=x;d++)
    if(x%d==0)
      {
    ret/=d; ret*=(d-1);
    while(x%d==0)x/=d;
      }
  if(x>1)ret/=x,ret*=(x-1);
  return ret%md;
}
void cal(ll x)
{
  tot=0;
  for(ll i=2;i*i<=x;i++)
    if(x%i==0)
      {
    p[++tot]=i;q[tot]=0;
    while(x%i==0)x/=i,q[tot]++;
      }
  if(x>1)p[++tot]=x,q[tot]=1;
}
void dfs(int cr,ll nw,ll phi)
{
  if(cr>tot){ans+=mul(F(n/nw,tmd),phi,tmd);upd(ans,tmd);return;}
  dfs(cr+1,nw,phi);
  nw*=p[cr];phi*=p[cr]-1;//needn't tmd
  dfs(cr+1,nw,phi);
  for(int i=2;i<=q[cr];i++)
    nw*=p[cr],phi*=p[cr],dfs(cr+1,nw,phi);
}
int main()
{
  scanf("%d",&T);
  while(T--)
    {
      scanf("%lld%d",&n,&a);
      fx=(n%mod==0); if(fx)tmd=M; else tmd=mod;
      init();  ans=0;
      cal(n); dfs(1,1,1);
      /*
      for(ll d=1;d*d<=n;d++)//d=1
    if(n%d==0)
      {
        ll k=n/d;
        ans+=mul(F(d,md),Phi(k,md),md); upd(ans,md);
        if(k!=d)ans+=mul(F(k,md),Phi(d,md),md), upd(ans,md);//mul
      }
      */
      if(fx)ans/=mod,ans=ans*pw(n/mod,mod-2,mod)%mod;
      else ans=ans*pw(n,mod-2,mod)%mod;
      printf("%lld\n",ans);
    }
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/Narh/p/10074544.html