CF103 D. Time to Raid Cowavans

题目传送门:https://codeforces.com/problemset/problem/103/D

题目大意:
给你一串长度为(n)的序列(A),每次询问给一组((a,b)),求(sumlimits_{i=0}^{lfloorfrac{n-a}{b} floor}A_{a+bi})


考虑离线,对所有询问的(b)进行排序

然后依据(b)(sqrt n)的大小关系,分为两种处理方法

  • (b<sqrt n),对序列(A)求跨步为(b)的后缀和(S),直接输出(S_a)即可
  • (b>sqrt n),每次询问从(a)开始暴力向后跳,统计答案

时间复杂度分析:

  • (b<sqrt n)(b)仅有(sqrt n)种取值,每次取值需要(O(n))统计后缀和,输出同(b)的询问仅需(O(1)),故该部分时间复杂度为(O(nsqrt n))
  • (b>sqrt n)(b)的取值数为(O(n));但此时,每次暴力仅需要(O(sqrt n))的次数就可以统计完毕,故该部分时间复杂度为(O(nsqrt n))

综上所述,总时间复杂度为(O(nsqrt n))

/*program from Wolfycz*/
#include<map>
#include<cmath>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#define Fi first
#define Se second
#define ll_inf 1e18
#define MK make_pair
#define sqr(x) ((x)*(x))
#define pii pair<int,int>
#define int_inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
template<typename T>inline T frd(T x){
	int f=1; char ch=gc();
	for (;ch<'0'||ch>'9';ch=gc())	if (ch=='-')    f=-1;
	for (;ch>='0'&&ch<='9';ch=gc())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
template<typename T>inline T read(T x){
	int f=1; char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x<0)	putchar('-'),x=-x;
	if (x>9)	print(x/10);
	putchar(x%10+'0');
}
const int N=3e5;
int A[N+10];
ll S[N+10],Ans[N+10];
struct opt{
	int a,b,ID;
	opt(int _a=0,int _b=0,int _ID=0){a=_a,b=_b,ID=_ID;}
	bool operator <(const opt &tis)const{return b<tis.b;}
}B[N+10];
int main(){
//	freopen("data.in","r",stdin);
//	freopen("ycz.out","w",stdout);
	int n=read(0),len=sqrt(n);
	for (int i=0;i<n;i++)	A[i]=read(0);
	int m=read(0);
	for (int i=1;i<=m;i++){
		int a=read(0)-1,b=read(0);
		B[i]=opt(a,b,i);
	}
	sort(B+1,B+1+m);
	for (int i=1;i<=m;i++){
		if (B[i].b>=len){
			for (int j=B[i].a;j<n;j+=B[i].b)	Ans[B[i].ID]+=A[j];
			continue;
		}
		if (B[i].b!=B[i-1].b){
			for (int j=n-1;~j;j--){
				S[j]=A[j];
				if (j+B[i].b<n)	S[j]+=S[j+B[i].b];
			}
		}
		Ans[B[i].ID]=S[B[i].a];
	}
	for (int i=1;i<=m;i++)	printf("%lld
",Ans[i]);
	return 0;
}
作者:Wolfycz
本文版权归作者和博客园共有,欢迎转载,但必须在文章开头注明原文出处,否则保留追究法律责任的权利
原文地址:https://www.cnblogs.com/Wolfycz/p/14956555.html