BZOJ 2301: [HAOI2011]Problem b
题目
2301: [HAOI2011]Problem b
Time Limit: 50 Sec Memory Limit: 256 MBDescription
对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数。
Input
第一行一个整数n,接下来n行每行五个整数,分别表示a、b、c、d、k
Output
共n行,每行一个整数表示满足要求的数对(x,y)的个数
Sample Input
2
2 5 1 5 1
1 5 1 5 2
2 5 1 5 1
1 5 1 5 2
Sample Output
14
3
HINT
100%的数据满足:1≤n≤50000,1≤a≤b≤50000,1≤c≤d≤50000,1≤k≤50000
题解
这道题目,我自己推得公式是sigma{miu[p]*(b/kp-(a-1)/kp)*(d/kp-(c-1)/kp)},这样是O(nd)的复杂度。还是TLE了,我不明觉厉,果然还是太弱!然后看网上的题解真是ORZ啊!
代码
/*Author:WNJXYK*/ #include<cstdio> #include<iostream> #include<cstring> #include<string> #include<algorithm> #include<queue> #include<set> #include<map> using namespace std; #define LL long long #define Inf 2147483647 #define InfL 10000000000LL inline void swap(int &x,int &y){int tmp=x;x=y;y=tmp;} inline void swap(LL &x,LL &y){LL tmp=x;x=y;y=tmp;} inline int remin(int a,int b){if (a<b) return a;return b;} inline int remax(int a,int b){if (a>b) return a;return b;} inline LL remin(LL a,LL b){if (a<b) return a;return b;} inline LL remax(LL a,LL b){if (a>b) return a;return b;} const int Maxn=50000; int miu[Maxn+10]; inline void getMiu(){ for (int i=1;i<=Maxn;i++){ int target=i==1?1:0; int delta=target-miu[i]; miu[i]=delta; for (int j=i+i;j<=Maxn;j+=i) miu[j]+=delta; } for (int i=2;i<=Maxn;i++) miu[i]+=miu[i-1]; } inline LL getAns(int n,int m){ if (n>m) swap(m,n); LL last; LL ret=0; for (LL i=1;i<=n;i=last+1){ last=remin(n/(n/i),(m/(m/i))); ret+=((LL)miu[last]-(LL)miu[i-1])*(m/i)*(n/i); } return ret; } int T; int a,b,c,d,k; LL Ans=0; int main(){ getMiu(); scanf("%d",&T); for (;T--;){ scanf("%d%d%d%d%d",&a,&b,&c,&d,&k); a-=1;c-=1; a/=k;b/=k;c/=k;d/=k; Ans=getAns(b,d)+getAns(a,c)-getAns(a,d)-getAns(b,c); printf("%lld\n",Ans); } return 0; }