POJ3468:A Simple Problem with Integers

浅谈分块:https://www.cnblogs.com/AKMer/p/10369816.html

题目传送门:http://poj.org/problem?id=3468

分块裸题。对于每个块记录权值和与加标记即可。详情见代码。

时间复杂度:\(O(n\sqrt{n})\)

空间复杂度:\(O(n)\)

代码如下:

#include <cmath>
#include <cstdio>
using namespace std;
typedef long long ll;

const int maxn=1e5+5;

char s[5];
ll sum[320];
int n,m,block;
int tag[320],val[maxn];
int bel[maxn],l[320],r[320];

int read() {
	int x=0,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*10+ch-'0';
	return x*f;
}

int main() {
	n=read(),m=read();block=sqrt(n);
	for(int i=1;i<=n;i++) {
		val[i]=read();
		bel[i]=(i-1)/block+1,sum[bel[i]]+=val[i];
		if(bel[i]!=bel[i-1])r[bel[i-1]]=i-1,l[bel[i]]=i;
	}r[bel[n]]=n;
	for(int i=1;i<=m;i++) {
		scanf("%s",s+1);
		int L=read(),R=read();
		if(s[1]=='Q') {
			ll res=0;
			if(bel[L]==bel[R]) {
				for(int j=L;j<=R;j++)
					res+=val[j]+tag[bel[L]];
			}
			else {
				for(int j=bel[L]+1;j<bel[R];j++)
					res+=sum[j]+1ll*tag[j]*(r[j]-l[j]+1);
				for(int j=L;j<=r[bel[L]];j++)
					res+=val[j]+tag[bel[L]];
				for(int j=l[bel[R]];j<=R;j++)
					res+=val[j]+tag[bel[R]];
			}
			printf("%lld\n",res);
		}
		else {
			int x=read();
			if(bel[L]==bel[R]) {
				for(int j=L;j<=R;j++)
					val[j]+=x,sum[bel[j]]+=x;
			}
			else {
				for(int j=bel[L]+1;j<bel[R];j++)
					tag[j]+=x;
				for(int j=L;j<=r[bel[L]];j++)
					val[j]+=x,sum[bel[L]]+=x;
				for(int j=l[bel[R]];j<=R;j++)
					val[j]+=x,sum[bel[R]]+=x;
			}
		}
	}
	return 0;
}
posted @ 2019-02-13 15:37  AKMer  阅读(105)  评论(0编辑  收藏  举报