signed

QiShunwang

“诚信为本、客户至上”

CodeForces -438D The Child and Sequence (线段树区间取余)

2020/12/29 0:30:02   来源:

题目链接:点击这里

题目大意:
给定一个长度为 n n n 的序列 a 1 , a 2 , . . . , a n a_1,a_2,...,a_n a1,a2,...,an ,对序列进行单点修改、区间取余和区间查询

题目分析:
有一个很经典的结论:
a m o d    p < a 2 ( a > p ) a \mod p<\frac a2(a>p) amodp<2a(a>p)
证明:
p ≤ a 2 p\le \frac a2 p2a a m o d    p < a 2 a \mod p< \frac a2 amodp<2a 显然成立
p > a 2 p>\frac a2 p>2a ,有 2 p > a 2p>a 2p>a 此时 a m o d    p = a − p < a 2 a\mod p=a-p<\frac a2 amodp=ap<2a
综上 a m o d    p < a 2 ( a > p ) a \mod p<\frac a2(a>p) amodp<2a(a>p)
有了这个结论后我们就很容易得出一个数 x x x 最多被取余 l o g x logx logx 次,因此我们可以仿照区间开方的思路对于维护区间最大值然后在最大值小于 p p p 时再暴力取余即可

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
#define int ll
using namespace std;
ll read()
{
	ll res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 5e5+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
struct sgt{
	int val,maxx;
}a[maxn<<2];
int n,m,sco[maxn];
char s[3];
void pushup(int root)
{
	a[root].val = a[root<<1].val+a[root<<1|1].val;
	a[root].maxx = max(a[root<<1].maxx,a[root<<1|1].maxx);
}
void build(int root,int l,int r)
{
	if(l == r)
	{
		a[root].val = a[root].maxx = read();
		return ;
	}
	int mid = l+r>>1;
	build(root<<1,l,mid);
	build(root<<1|1,mid+1,r);
	pushup(root);
}
void updat(int root,int l,int r,int pos,int val)
{
	if(l == r)
	{
		a[root].val = a[root].maxx = val;
		return ;
	}
	int mid = l+r>>1;
	if(pos <= mid) updat(root<<1,l,mid,pos,val);
	else updat(root<<1|1,mid+1,r,pos,val);
	pushup(root);
}
void updat_mod(int root,int l,int r,int ql,int qr,int val)
{
	if(l>qr || r<ql || a[root].maxx < val) return ;
	if(l == r)
	{
		a[root].val = a[root].val%val;
		a[root].maxx = a[root].maxx%val;
		return ;
	}
	int mid = l+r>>1;
	updat_mod(root<<1,l,mid,ql,qr,val);
	updat_mod(root<<1|1,mid+1,r,ql,qr,val);
	pushup(root);
}
int query(int root,int l,int r,int ql,int qr)
{
	if(l>qr || r<ql) return 0;
	if(l>=ql && r<=qr) return a[root].val;
	int mid = l+r>>1;
	return query(root<<1,l,mid,ql,qr)+query(root<<1|1,mid+1,r,ql,qr);
}
signed main()
{
	n = read(),m = read();
	build(1,1,n);
	while(m--)
	{
		int opt = read();
		if(opt == 1) 
		{
			int x = read(),y = read();
			printf("%lld\n",query(1,1,n,x,y));
		}
		else if(opt == 2)
		{
			int x = read(),y = read(),val = read();
			updat_mod(1,1,n,x,y,val);
		}
		else if(opt == 3)
		{
			int x = read(),y = read();
			updat(1,1,n,x,y);
		}
	}
	return 0;
}