题目描述
小(C)最近在学习线性函数,线性函数可以表示为:(f(x) = kx + b)。
现在小(C)面前有(n)个线性函数 (f_i(x)=k_ix+b_i),他对这(n)个线性函数执行(m)次操作。
每次可以:
1.(M i k b) 代表把第(i)个线性函数改为:(f_i(x)=kx+b)。
2.(Q l r x) 返回(f_r(f_{r-1}(...f_l(x))) mod 10^9+7)。
题解
用线段树维护每一段区间的(k)和(b)的值,区间合并时,假设左区间是(k_1)和(b_1),右区间是(k_2)和(b_2),那么合并后就是(k_2(k_1x+b_1)+b_2),即(k_1k_2)和(k_2b_1+b_2)。
依次维护修改即可,详见代码。
#include <iostream>
#include <cstdio>
#define ll long long
using namespace std;
const int mod = 1e9 + 7;
const int N = 5e5 + 5;
int n, m;
ll K[N << 2], B[N << 2];
struct node {ll k, b;}L, R, em;
char s[5];
inline int read()
{
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') {x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar();}
return x * f;
}
void update(int k)
{
K[k] = K[k << 1] * K[k << 1 | 1] % mod;
B[k] = (K[k << 1 | 1] * B[k << 1] % mod + B[k << 1 | 1]) % mod;
}
void build(int k, int l, int r)
{
if(l == r)
{
K[k] = read(); B[k] = read();
return;
}
int mid = (l + r) >> 1;
build(k << 1, l, mid);
build(k << 1 | 1, mid + 1, r);
update(k);
}
void change(int k, int l, int r, int x, int kk, int bb)
{
if(l == r) return K[k] = kk, B[k] = bb, void();
int mid = (l + r) >> 1;
if(x <= mid) change(k << 1, l, mid, x, kk, bb);
else change(k << 1 | 1, mid + 1, r, x, kk, bb);
update(k);
}
node query(int k, int l, int r, int x, int y)
{
if(x <= l && r <= y) return node{K[k], B[k]};
int mid = (l + r) >> 1; ll lk = -1, lb = -1, rk = -1, rb = -1;
if(x <= mid)
{
L = query(k << 1, l, mid, x, y);
lk = L.k; lb = L.b;
}
if(y > mid)
{
R = query(k << 1 | 1, mid + 1, r, x, y);
rk = R.k; rb = R.b;
}
if(lk == -1 && lb == -1) return node{rk, rb};
else if(rk == -1 && rb == -1) return node{lk, lb};
else return node{lk * rk % mod, (lb * rk % mod + rb) % mod};
}
int main()
{
n = read(); m = read(); build(1, 1, n);
int l, r, x, kk, bb;
while(m -- > 0)
{
scanf("%s", s);
if(s[0] == 'M')
{
x = read(); kk = read(); bb = read();
change(1, 1, n, x, kk, bb);
}
else
{
l = read(); r = read(); x = read();
em = query(1, 1, n, l, r);
printf("%lld
", (em.k * x % mod + em.b) % mod);
}
}
return 0;
}