BZOJ2301 HAOI2011 Problem b

2301: [HAOI2011]Problem b

Time Limit: 50 Sec  Memory Limit: 256 MB

Description

瀵逛簬缁欏嚭鐨刵涓闂紝姣忔姹傛湁澶氬皯涓暟瀵?x,y)锛屾弧瓒砤≤x≤b锛宑≤y≤d锛屼笖gcd(x,y) = k锛実cd(x,y)鍑芥暟涓簒鍜寉鐨勬渶澶у叕绾︽暟銆?

Input

绗竴琛屼竴涓暣鏁皀锛屾帴涓嬫潵n琛屾瘡琛屼簲涓暣鏁帮紝鍒嗗埆琛ㄧずa銆乥銆乧銆乨銆乲

Output

鍏眓琛岋紝姣忚涓€涓暣鏁拌〃绀烘弧瓒宠姹傜殑鏁板(x,y)鐨勪釜鏁?/span>

Sample Input

2
2 5 1 5 1
1 5 1 5 2

Sample Output

14
3

HINT

100%鐨勬暟鎹弧瓒筹細1≤n≤50000锛?≤a≤b≤50000锛?≤c≤d≤50000锛?≤k≤50000

 

銆€銆€姝hВ鏄樉鑰屾槗瑙佺殑鏁拌銆?/span>

銆€銆€鐪嬭杩欎釜棰樼洰鍙互椹笂鎯冲埌瀹规枼鍘熺悊锛?/span>

銆€銆€璁剧瓟妗堟槸f(a,b,c,d,k)锛岄偅涔堜竴瀹氭湁

銆€銆€銆€銆€f(a,b,c,d,k)=f(1,b,1,d,k)-f(1,a-1,1,d,k)-f(1,b,1,c-1,k)+f(1,a-1,a,c-1,k)锛?br />

銆€銆€鐜板湪灏辨槸瑕佹眰f(1,n,1,m,k)浜嗐€?/span>

銆€銆€闂杞寲涓烘眰4娆?ldquo;1<=x<=n,1<=y<=m,gcd(x,y)=k鐨勬暟瀵规暟”銆?br />

銆€銆€杩欎釜灏辨槸寰坰imple鐨勮帿姣旈笩鏂嚱鏁伴浜哘wQ銆?/span>

銆€銆€BZOJ2301 HAOI2011 Problem b_第1张图片

銆€銆€鐒跺悗灏辨槸鍙埍鐨勬暟璁哄垎鍧楋紝澶嶆潅搴(√n)銆?/span>

銆€銆€鎵€浠ユ€诲鏉傚害灏辨槸O(T√n)浜嗐€?/span>

#include    
#include    
#include    
#include    
#include    
#include    
#include    
#include    
#include    
#define LL long long int
#define dob double
using namespace std;

const int N = 50010;
int P[N],tot,miu[N],vis[N],k;
LL Ans;

int gi()
{
  int x=0,res=1;char ch=getchar();
  while(ch>'9'||ch<'0'){if(ch=='-')res*=-1;ch=getchar();}
  while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
  return x*res;
}

inline void prepare(){
  miu[1]=1;
  for(int i=2;ii){
    if(!vis[i])miu[i]=-1,P[++tot]=i;
    for(int j=1;j<=tot;++j){
      if(i*P[j]>=N)break;
      vis[i*P[j]]=1;
      if(i%P[j])miu[i*P[j]]=-miu[i];
      else{miu[i*P[j]]=0;break;}
    }
  }
  for(int i=2;ii)
    miu[i]+=miu[i-1];
}

inline int gcd(int a,int b){return b?gcd(b,a%b):a;}

inline int _(int x,int g){
  return x/k+(x%k?1:0)*g;
}

inline LL calc(int n,int m){
  LL ans=0;
  if(n>m)swap(n,m);
  for(int gl=1,gr;gl<=n;gl=++gr){
    gr=min(n/(n/gl),m/(m/gl));
    ans+=1ll*(miu[gr]-miu[gl-1])*1ll*(n/gl)*1ll*(m/gr);
  }
  return ans;
}

int main()
{
  prepare();int Case=gi();
  while(Case--){
    int a=gi(),b=gi(),c=gi(),d=gi();k=gi();
    a=_(a,1);b=_(b,0);c=_(c,1);d=_(d,0);
    //if(b>d)swap(a,c),swap(b,d);
    Ans=calc(b,d)-calc(a-1,d)-calc(b,c-1)+calc(a-1,c-1);
    printf("%lld\n",Ans);
  }
  return 0;
}
Problem B

 

 

 

 

 

 

你可能感兴趣的:(BZOJ2301 HAOI2011 Problem b)