题目大意:
初始给定一个长度为的序列,有次操作:
操作1:给定,询问的最大子段和
操作2:给定,表明将的值改为
看到大家都是用线段树直接维护的区间最大子段和QwQ
不过本题可以用动态dp的方法来做……
首先考虑将最大子段和的普通dp方程写出来:(这里设数列为)
表示由的子序列所构成的且选入最大子段和的最后一个数为的最大子段和
表示由的子序列所构成的最大子段和
故有:
根据动态dp的套路,将这个方程写成矩阵形式,并更改矩阵乘法的定义:
将原来的定义(这里设矩阵相乘得到矩阵,并要求矩阵的列数等于矩阵的行数):
变为:
不难发现max同样拥有结合律,故新定义的矩阵乘法同样具有结合律
发现由于的转移需依靠,而在转移时是未知的(即我们不便于将同时列在一个矩阵中),故可将拆为进行转移(即)
这样再写成矩阵的形式:
检验一下我们写的是否正确:
将矩阵乘开得:
对比前文的式子,看来我们写的是正确的……
这样对于序列中每一个元素,均有矩阵:
不妨设所对应的矩阵为,不难发现,当我们询问的最大子段和时,只需将相乘即可;
容易想到使用线段树来维护区间内矩阵的乘积,即对于矩阵序列,建一棵支持单点修改区间查询的线段树即可。
Code:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
template<typename T>
inline bool chkmax(T &x, const T &y) {return x < y ? (x = y, true) : false;}
const int inf = 0x3f3f3f3f;
const int maxn = 500010;
int n, m, score[maxn];
struct Matrix
{
int v[3][3];//这里矩阵下标是从v[0][0]开始
Matrix operator * (const Matrix &rhs) const
{
Matrix res;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
res.v[i][j] = -inf;
}
}
for (int i = 0; i < 3; ++i)
{
for (int k = 0; k < 3; ++k)//矩阵乘法优化
{
for (int j = 0; j < 3; ++j)
{
chkmax(res.v[i][j], v[i][k] + rhs.v[k][j]);
}
}
}
return res;
}
};
class Segtree
{
#define lson root << 1
#define rson root << 1 | 1
private:
Matrix val[maxn << 2];
inline void pushup(int root) {val[root] = val[lson] * val[rson];}
public:
void build(int s, int e, int root)
{
if (s == e)
{
val[root].v[0][0] = val[root].v[1][0] =
val[root].v[0][2] = val[root].v[1][2] = score[s];
val[root].v[0][1] = val[root].v[2][0] =
val[root].v[2][1] = -inf;
val[root].v[1][1] = val[root].v[2][2] = 0;
//按照前文所述构造a[i]对应的A[i]
return;
}
int mid = (s + e) >> 1;
build(s, mid, lson);
build(mid + 1, e, rson);
pushup(root);
}
void modify(int s, int e, int pos, int root, int k)
{
if (s == e)
{
val[root].v[0][0] = val[root].v[1][0] =
val[root].v[0][2] = val[root].v[1][2] = k;
return;
}
int mid = (s + e) >> 1;
if (pos <= mid) modify(s, mid, pos, lson, k);
else modify(mid + 1, e, pos, rson, k);
pushup(root);
}
Matrix query(int s, int e, int ql, int qr, int root)
{
if (ql <= s && e <= qr) return val[root];
int mid = (s + e) >> 1;
if (ql <= mid && qr > mid)
return query(s, mid, ql, qr, lson) *
query(mid + 1, e, ql, qr, rson);
else if (ql <= mid) return query(s, mid, ql, qr, lson);
else return query(mid + 1, e, ql, qr, rson);
}
#undef lson
#undef rson
}tree;
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) scanf("%d", score + i);
tree.build(1, n, 1);
int opt, x, y;
Matrix res;
while (m--)
{
scanf("%d%d%d", &opt, &x, &y);
if (opt == 1)
{
if (x > y) swap(x, y);//题目中不保证x < y,当x > y时,需交换
res = tree.query(1, n, x, y, 1);
printf("%d\n", max(res.v[1][0], res.v[1][2]));//注意需选f[i],g[i]中最优的
}
else
tree.modify(1, n, x, 1, y);
}
return 0;
}