题解:P17112 「FAOI-R13」Hi, story
鸣谢:@xzy_AK_IOI 巨佬的题解
我们需要将区间加不同值转化为维护关于“操作次数的线性表达式”的
对于位置
我们把它写成
假设有两个这样的表达式:
我们想求
回忆整数的辗转相除:
这里同样,我们可以把
于是:
重复这个过程,直到某个表达式的
- 最终常数项
c 需要包含之前的常数和新的常数:c = \gcd(c', c_1, c_2)
对线段树的每个节点,我们存下该节点对应区间的合并结果 tag,表示该区间所有位置整体被操作过的次数(即
当我们对一个区间执行操作
-
当前区间内所有位置的
x 增加1 -
对于节点上已经合并好的表达式
\gcd(kx + a, c) ,x 变成x+1 后:\gcd(k(x+1) + a, c) = \gcd(kx + (a+k),c) 所以只需要把
a 加上k ,并给tag加1 。这样就能保证合并任意两个表达式时x 是相同的,实际上都是0 ,下文也会再提及。
这样,每个节点内维护的表达式总是基于“当前节点内所有位置的操作次数相同”这一假设。由于操作是区间加,我们只需要在修改时打标记,查询时把标记下传(pushdown),保证子节点和父节点的
查询一个区间
需要注意的是,最终答案可能为负,要取绝对值。因为上文中两个线性表达式合并时出现了减法,或引进负号,而符号并不影响
时间复杂度
:::info[Code]
#include<bits/stdc++.h>
#define int long long
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
#define lson ls(id),l,mid
#define rson rs(id),mid+1,r
using namespace std;
const int N=7e5+5;
int n,q,a[N],b[N],tag[N<<2];
struct Node
{
int k,a,c;//k=b[i],a=a[i],gcd(k*x+a,c)
bool operator==(const Node &t)const{return k==t.k&&a==t.a&&c==t.c;}
}tr[N<<2];
int gcd(int a,int b){return b?gcd(b,a%b):a;}
Node egcd(int k1,int a1,int k2,int a2)
{
if(!k2) return (Node){k1,a1,a2};
return egcd(k2,a2,k1%k2,a1-(k1/k2)*a2);
}
inline Node merge(Node p,Node q)
{
int k1=p.k, a1=p.a, c1=p.c, k2=q.k, a2=q.a, c2=q.c;
Node tmp=egcd(k1,a1,k2,a2);
tmp.c=gcd(tmp.c,gcd(c1,c2));
return tmp;
}
inline void pushup(int id)
{
tr[id]=merge(tr[ls(id)],tr[rs(id)]);
}
inline void pushdown(int id)
{
tr[ls(id)].a+=tag[id]*tr[ls(id)].k,tag[ls(id)]+=tag[id];
tr[rs(id)].a+=tag[id]*tr[rs(id)].k,tag[rs(id)]+=tag[id];
tag[id]=0;
}
void build(int id,int l,int r)
{
tag[id]=0;
if(l==r)
{
tr[id]=(Node){b[l],a[l],0};
return;
}
int mid=l+r>>1;
build(lson),build(rson);
pushup(id);
}
void upt(int id,int l,int r,int x,int y)
{
if(x<=l&&r<=y)
{
tr[id].a+=tr[id].k,tag[id]++;
return;
}
pushdown(id);
int mid=l+r>>1;
if(mid>=x) upt(lson,x,y);
if(mid<y) upt(rson,x,y);
pushup(id);
}
Node qry(int id,int l,int r,int x,int y)
{
if(x<=l&&r<=y) return tr[id];
pushdown(id);
int mid=l+r>>1;Node res=(Node){-1,-1,-1};
if(mid>=x) res=qry(lson,x,y);
if(mid<y)
{
if(res==(Node){-1,-1,-1}) res=qry(rson,x,y);
else res=merge(res,qry(rson,x,y));
}
return res;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int CSN,op,l,r;cin>>CSN;
while(CSN--)
{
cin>>n>>q;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) cin>>b[i];
build(1,1,n);
while(q--)
{
cin>>op>>l>>r;
if(op&1) upt(1,1,n,l,r);
else
{
Node tmp=qry(1,1,n,l,r);
cout<<labs(gcd(tmp.a,tmp.c))<<'\n';
}
}
}
return 0;
}
:::