跳到正文

题解

题解:P4635 [SHOI2011] 改进代码

Inracle约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年6月19日
更新
2026年6月19日
篇幅
约 4 分钟
获赞
1
题目
P4635

版本

  1. v1当前

自认为是简单好理解的一篇。

题意就是区间加并对 pp 取模,求 ∑i=lr−1[ai>ai+1]\sum_{i=l}^{r-1}[a_i > a_{i+1}]。

考虑差分,令 bi=ai−ai−1b_i = a_i - a_{i-1}。

因为是在模 pp 的意义下的,所以我们可以处理一下,使 bb 满足 0≤bi<p0 \le b_i < p。

这个时候令 ci=∑j=1ibjc_i = \sum_{j=1}^{i}b_j,即前缀和的 bb,有 ai≡ci(modp)a_i \equiv c_i\pmod p,那么对着取模后的 cc 做和对着原来的 aa 做是等价的。

因为有 0≤bi<p0 \le b_i < p,即 0≤ci−ci−1<p0 \le c_i - c_{i-1} <p 这个很美妙的东西,所以你就会发现:

当且仅当存在 k(k∈Z+)k(k \in \Z^+) 使得 ci<kp≤ci+1c_i< kp \le c_{i+1} 时,有 ci mod p>ci+1 mod pc_i \bmod p > c_{i+1} \bmod p。

而且因为 0≤ci−ci−1<p0 \le c_i - c_{i-1} <p,所以至多只会有一个 k(k∈Z+)k(k \in \Z^+) 使得 ci<kp≤ci+1c_i< kp \le c_{i+1}。

这就很好做了,转化成统计 (cl,cr](c_l,c_r] 之间 kp(k∈Z+)kp(k \in \Z^+) 的和即可,使用树状数组,时间复杂度 O(nlog⁡n)O(n \log n)。

代码

短短的代码。

C++
#include<bits/stdc++.h>
#define i128 __int128
#define ll long long
#define ull unsigned long long
#define db double
#define ldb long double
#define Pii pair<int,int>
#define fi first
#define se second
#define f(x,y) fixed<<setprecision(y)<<x
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,rp,stdin),p1==p2)?EOF:*p1++)

using namespace std;
const int N=1e5+10;
const int rp=1e6+10;

int n,m,mod,p[N]; ll b[N],c[N];
char buf[rp],*p1=buf,*p2=buf;

inline int read()
{
	int x=0,f=1; char c=0;
	while(!isdigit(c)) {if(c=='-') f=-1; c=gc();}
	while(isdigit(c)) x=(x<<3)+(x<<1)+(c^48),c=gc();
	return x*f;
}

inline char read_ch()
{
	char c=0;
	while((!isalpha(c))&&(!isdigit(c))) c=gc();
	return c;
}

inline void upd(int x,ll v)
{
	if(b[x]+v>=mod) v-=mod; b[x]+=v;//保证 b 小于 p
	while(x<=n) c[x]+=v,x+=x&-x;
}

inline ll get(int x)
{
	ll v=0;
	while(x) v+=c[x],x-=x&-x;
	return v;
}

signed main()
{
	cin.tie(0)->sync_with_stdio(0);
	cin>>n>>m>>mod; int op,l,r,x;
	for(int i=1;i<=n;++i)
		cin>>p[i],upd(i,((p[i]-p[i-1])%mod+mod)%mod);//差分
	while(m--)
	{
		cin>>op>>l>>r;
		if(op==1) cin>>x,x%=mod,upd(l,x),upd(r+1,mod-x);
		else cout<<get(r)/mod-get(l)/mod<<"\n";//kp in (c_l,c_r]
	}
	return 0;
}
原文