One day, Peter came across a function which looks like:
- F(1, X) = X mod A1.
- F(i, X) = F(i - 1, X) mod Ai, 2 ≤ i ≤ N.
Peter wants to know the number of solutions for equation F(N, X) = Y, where Y is a given number.
Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers N and M (2 ≤ N ≤ 105, 0 ≤ M ≤ 109).
The second line contains N integers: A1, A2, ..., AN (1 ≤ Ai ≤ 109).
The third line contains an integer Q (1 ≤ Q ≤ 105) - the number of queries. Each of the following Q lines contains an integer Yi (0 ≤ Yi ≤ 109), which means Peter wants to know the number of solutions for equation F(N, X) = Yi.
Output
For each test cases, output an integer S = (1 ⋅ Z1 + 2 ⋅ Z2 + ... + Q ⋅ ZQ) mod (109 + 7), where Zi is the answer for the i-th query.
Sample Input
1 3 5 3 2 4 5 0 1 2 3 4
Sample Output
8
Hint
The answer for each query is: 4, 2, 0, 0, 0.
这里挖一个坑!区间取模有点难以理解
【题意】
有n(1e5)个数字a[](1e9),我们有q(1e5)个询问。
对于每个询问,想问你——有多少个[0,m](m∈[0,1e9])范围的数,满足其mod a[1] mod a[2] mod a[3] mod ... mod a[n]== b[i]
(b[]是1e9范围的数)
【类型】
暴力
复杂度分析
【分析】
这道题的关键之处,在于要想到——
取模不仅仅是一个数可以取模,一个区间我们也可以做取模处理。
进一步我们发现,取模得到的区间左界必然都为0
一个区间[0,r)的数 mod a[i],
如果r>a[i],那么——
这个区间会变成r/a[i]个[0,a[i])的区间,以及一个[0,r%a[i])的区间
这样,我们对于每个a[i],我们就把所有>a[i]的区间都做处理。
在所有处理都完成之后,我们可以用双指针的方式处理所有询问的答案
【时间复杂度&&优化】
O(nlognlogn)
这题的复杂度为什么是这样子呢?
对于一个数,这个数做连续若干次的取模运算, 数值变化次数不会超过logn次。
于是我们以区间做取模运算,数值变化次数不会超过nlogn次。
然后加上map的复杂度,总的复杂度不过nlognlogn,可以无压力AC之。
代码
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5+10; const int mod = 1e9+7; map<ll,ll> mop; map<ll,ll>::iterator it; pair<ll,ll> a[maxn]; int main() { int casenum; ll n,m; int q; scanf("%d", &casenum); for (int casei = 1; casei <= casenum; ++casei) { mop.clear(); scanf("%lld%lld", &n, &m); mop[m + 1] = 1; for (int i = 1; i <= n; ++i) { ll x; scanf("%lld", &x); while(1) { it = mop.upper_bound(x); if (it == mop.end())break; mop[x] += it->first / x * it->second; if(it->first%x)mop[it->first%x] += it->second; mop.erase(it); } } ll sum = 0; for (it = mop.begin(); it != mop.end(); ++it)sum += it->second; //printf("%lld\n",sum); //for (it = mop.begin(); it != mop.end(); it++) printf("%lld %lld\n",it->first,it->second); scanf("%d", &q); for (int i = 1; i <= q; ++i)scanf("%lld", &a[i].first), a[i].second = i; sort(a + 1, a + q + 1); it = mop.begin(); ll ans = 0; for (int i = 1; i <= q; ++i) { while (a[i].first >= it->first) { sum -= it->second; ++it; if (it == mop.end())break; } if (it == mop.end())break; ans = (ans + (ll)sum * a[i].second) % mod; } printf("%lld\n", ans); } return 0; }