[BZOJ2301][HAOI2011]Problem b

2301: [HAOI2011]Problem b

Time Limit: 50 Sec  Memory Limit: 256 MB Submit: 5998  Solved: 2734 [Submit][Status][Discuss]

Description

st1\:*{behavior:url(#ieooui) }

对于给出的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



Sample Output


14

3



HINT

100%的数据满足:1≤n≤50000,1≤a≤b≤50000,1≤c≤d≤50000,1≤k≤50000

 

把询问拆成四个,就和[POI2007]ZAP一样了

#pragma GCC optimize("O2")
#include <cstdio>
#include <algorithm>
using namespace std;
char buf[10000000], *ptr = buf - 1;
inline int readint(){
    int n = 0;
    while(*++ptr < '0' || *ptr > '9');
    while(*ptr <= '9' && *ptr >= '0') n = (n << 1) + (n << 3) + (*ptr++ & 15);
    return n;
}
const int maxn = 50000 + 10;
bool mark[maxn] = {false};
int mu[maxn], sum[maxn];
int pri[maxn], prn = 0;
void shai(){
    mu[1] = 1;
    for(int i = 2; i <= 50000; i++){
        if(!mark[i]){
            pri[++prn] = i;
            mu[i] = -1;
        }
        for(int j = 1; j <= prn && pri[j] * i <= 50000; j++){
            mark[i * pri[j]] = true;
            if(i % pri[j] == 0){
                mu[i * pri[j]] = 0;
                break;
            }
            else mu[i * pri[j]] = -mu[i];
        }
    }
    sum[0] = 0;
    for(int i = 1; i <= 50000; i++)
        sum[i] = sum[i - 1] + mu[i];
}
inline int work(int n, int m){
    if(n > m) swap(n, m);
    int ans = 0, pos;
    for(int i = 1; i <= n; i = pos + 1){
        pos = min(n / (n / i), m / (m / i));
        ans += (sum[pos] - sum[i - 1]) * (n / i) * (m / i);
    }
    return ans;
}
int main(){
    fread(buf, sizeof(char), sizeof(buf), stdin);
    shai();
    int n = readint();
    int a, b, c, d, k;
    while(n--){
        a = readint();
        b = readint();
        c = readint();
        d = readint();
        k = readint();
        printf("%d\n", work(b / k, d / k) + work((a - 1) / k, (c - 1) / k) - work((a - 1) / k, d / k) - work(b / k, (c - 1) / k));
    }
    return 0;
}

 

posted @ 2017-10-05 21:56  jzyy  阅读(104)  评论(0编辑  收藏  举报