ZOJ-4029-Now Loading!!!(2018浙江第15届省赛)(思维+枚举优化+二分)

https://zoj.pintia.cn/problem-sets/91827364500/problems/91827370263


DreamGrid has  integers . DreamGrid also has  queries, and each time he would like to know the value of

for a given number , where , .

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

初始的想法是对于每次询问,直接去算公式,这样的时间复杂度是O(n*m)对于题给数据显然是超时的,

现在我们考虑怎么优化.

可以看到出次方或者带log的如果出现可以转化枚举的方向。因为这一部分的值比较小。(比较套路叭)

(比如p = 2,ai = 在[2^30+1,2^31-1]之间时),分母最大也只有31

考虑到公式中的分母如此之小,题目应该从这里入手

我们可以预先处理A数组除以分母的前缀和。

然后查询的时候,看1~p^1之间有多少a[i]在里面,p^1+1~p^2之间有多少a[i]在里面,p^2+1~p^3之间有多少a[i]在里面,这部分用二分就可以了。然后前缀和统计。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e5+100;
typedef long long LL;
const LL mod=1e9;
LL a[maxn],sum[40][maxn];
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL t;cin>>t;
  while(t--)
  {
  	LL n,m;cin>>n>>m;
  	for(LL i=1;i<=n;i++) cin>>a[i];
  	sort(a+1,a+1+n); 
  	for(LL i=1;i<=32;i++){
  		sum[i][0]=0;
  		for(LL j=1;j<=n;j++)
		  {
		  	  sum[i][j]=(sum[i][j-1]+a[j]/i)%mod;
		  }	
	}
	LL ans=0;
	for(LL j=1;j<=m;j++)
	{
		LL p;cin>>p;
		LL temp=0;
		LL pos=1;
		for(LL i=1;i<=32;i++)
		{
			LL l=upper_bound(a+1,a+1+n,pos)-a;//a[i]在1~p范围内有多少,在p+1~p^2范围内有多少,在p^2+1~p^3范围内有多少.... 
			if(l>n) break;
			LL r=upper_bound(a+1,a+1+n,pos*p)-a;
			if(l==n+1) continue;
			temp=(temp+(sum[i][r-1]-sum[i][l-1]))%mod;
			temp=(temp+mod)%mod;
			pos*=p;
		}
		ans=(ans+temp*j%mod)%mod;
	}
	cout<<ans<<endl;
  }
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/108819199