DreamGrid has integers . DreamGrid also has queries, and each time he would like to know the value of
Input
There are multiple test cases. The first line of input is an integer indicating the number of test cases. For each test case:
The first line contains two integers and () -- the number of integers and the number of queries.
The second line contains integers ().
The third line contains integers ().
It is guaranteed that neither the sum of all nor the sum of all exceeds .
Output
For each test case, output an integer , where is the answer for the -th query.
Sample Input
2 3 2 100 1000 10000 100 10 4 5 2323 223 12312 3 1232 324 2 3 5
Sample Output
11366 45619
题意:
求上述公式;
思路:
按部就班 n*n肯定超时 所以发现最大为2e9,也就是分母最大为31(2^32>2e9)。
枚举分母,然后二分查找数组a的下限和上限 利用前缀和;
复杂度
n*log*log;
代码实现:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=1e5+10;
const ll flag=2e9+10;
const ll mod=1e9;
ll a[maxn],p[maxn];
ll sum[40][maxn];
ll qow(ll n,ll m)
{
ll res=1;
// cout<<n<<m<<endl;
while(m)
{
// cout<<m<<endl;
if(m&1) res*=n;
n*=n;
m>>=1;
if(res>20001001000)return -1;
}
return res;
}
int main()
{
ll t;
scanf("%lld",&t);
while(t--)
{
ll n,m;
scanf("%lld%lld",&n,&m);
for(ll i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(ll i=1;i<=m;i++)
scanf("%lld",&p[i]);
sort(a+1,a+1+n);
for(int i=1;i<=31;i++)
{
sum[i][0]=0;
for(int j=1;j<=n;j++)
{
sum[i][j]=(sum[i][j-1]+a[j]/i);//前缀和log/i;
//cout<<sum[i][j]<<" ";
}
// cout<<endl;
}
ll result=0;
for(int k=1;k<=m;k++)
{
ll ans=0;
for(int i=1;i<=31;i++)
{
ll up,down;
down=qow(p[k],i-1);
up=qow(p[k],i);
if(down==-1)
break;
ll l,r,mid;
l=1;r=n+1;
//二分查找 最小的a【i】和最大的
if(down!=-1)//可以去掉可不去
while(l<r)
{
mid=(l+r)>>1;
if(a[mid]>down)
r=mid;
else
l=mid+1;
}
ll L=r;
l=1;r=n+1;
if(up!=-1)//坑点注意 up不能为-1;
while(l<r)
{
mid=(l+r)>>1;
if(a[mid]>up)
r=mid;
else
l=mid+1;
}
ll R=r-1;
if(L>n)
break;
if(L>R)
continue;
ans=(ans+sum[i][R]-sum[i][L-1])%mod;
ans=(ans+mod)%mod;
}
result=(result+ans*k%mod)%mod;
}
printf("%lld\n",result);
}
return 0;
}