P2522 [HAOI2011]Problem b
题意:
对于给出的 n 个询问,每次求有多少个数对 (x,y),满足 a≤x≤b,c≤y≤d,且 gcd(x,y)=k,gcd(x,y) 函数为 x 和 y 的最大公约数。
题解:
这个题跟P3455 [POI2007]ZAP-Queries很像,唯一的区别就是本题不是从1开始是从a开始,本题的公式是这样的:
∑x=ab∑y=cdgcd(x,y)=k\sum_{x=a}^{b}\sum_{y=c}^{d}\gcd(x,y)=k∑x=ab∑y=cdgcd(x,y)=k
两个求和公式分别是从a和c开始,而不是1开始
这怎么整?
这样:两个求和公式其实就是二维前缀和,如图,现在我们知道各点到(1,1)的面积,如何求小矩形的面积?sum=solve(b,d)-solve(b,a)-solve(c,b)+solve(a,c)
这样我们只需要求从1开始的求和公式,然后通过运算得到我们想要的指定范围
代码:
// Problem: P2522 [HAOI2011]Problem b
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P2522
// Memory Limit: 250 MB
// Time Limit: 2500 ms
// Data:2021-08-21 10:45:59
// By Jozky#include <bits/stdc++.h>
#include <unordered_map>
#define debug(a, b) printf("%s = %d\n", a, b);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
clock_t startTime, endTime;
//Fe~Jozky
const ll INF_ll= 1e18;
const int INF_int= 0x3f3f3f3f;
void read(){};
template <typename _Tp, typename... _Tps> void read(_Tp& x, _Tps&... Ar)
{x= 0;char c= getchar();bool flag= 0;while (c < '0' || c > '9')flag|= (c == '-'), c= getchar();while (c >= '0' && c <= '9')x= (x << 3) + (x << 1) + (c ^ 48), c= getchar();if (flag)x= -x;read(Ar...);
}
template <typename T> inline void write(T x)
{if (x < 0) {x= ~(x - 1);putchar('-');}if (x > 9)write(x / 10);putchar(x % 10 + '0');
}
void rd_test()
{
#ifdef LOCALstartTime= clock();freopen("in.txt", "r", stdin);
#endif
}
void Time_test()
{
#ifdef LOCALendTime= clock();printf("\nRun Time:%lfs\n", (double)(endTime - startTime) / CLOCKS_PER_SEC);
#endif
}
const int maxn= 5e5 + 9;
int mu[maxn];
int prim[maxn];
int tot= 0;
int tag[maxn];
int vis[maxn];
int sum[maxn];
void get_mu(int n)
{mu[1]= 1;tag[0]= tag[1]= 1;for (int i= 2; i <= n; i++) {if (!tag[i]) {prim[++tot]= i;mu[i]= -1;}for (int j= 1; j <= tot && i * prim[j] <= n; j++) {tag[i * prim[j]]= 1;if (i % prim[j] == 0)break;mu[i * prim[j]]= -mu[i];}}for (int i= 1; i <= n; i++) {sum[i]= sum[i - 1] + mu[i];}
}
int a, b, c, d, k;
ll solve(int b, int d)
{b/= k;d/= k;int minn= min(b, d);ll ans= 0;for (int l= 1, r; l <= minn; l= r + 1) {r= min(b / (b / l), d / (d / l));ans+= 1ll * (sum[r] - sum[l - 1]) * (b / l) * (d / l);}return ans;
}
int main()
{//rd_test();get_mu(500000);//cout << "--" << endl;int t;read(t);while (t--) {read(a, b, c, d, k);printf("%lld\n", solve(b, d) - solve(b, c - 1) - solve(a - 1, d) + solve(a - 1, c - 1));}return 0;//Time_test();
}