加c++代码给定一个长度为n的字符串,字符串只有4和7构成,因为BSNY认为只有4和7是幸运数。现在BSNY有m个任务给你,任务有2种: switch l r 把[l, r]区间内的4换成7,7换成4; count 计算这n个幸运数的最长不下降子序列长度。
时间: 2024-06-09 12:04:29 浏览: 113
RC4.rar_RC4 加解密 C++_RC4 界面_字符串 加解密
以下是参考代码,使用了线段树实现区间修改和查询最长不下降子序列长度。
```c++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1e6 + 10;
int n, m, a[MAXN];
struct Node {
int l, r;
int len, lmax, rmax, ans;
int tag;
} tr[MAXN << 2];
void pushup(Node &u, Node &lc, Node &rc) {
u.len = lc.len + rc.len;
u.lmax = lc.lmax;
if (lc.lmax == lc.len && a[u.lc] <= a[rc.lc]) u.lmax += rc.lmax;
u.rmax = rc.rmax;
if (rc.rmax == rc.len && a[rc.rc] <= a[lc.rc]) u.rmax += lc.rmax;
u.ans = max(max(lc.ans, rc.ans), lc.rmax + rc.lmax);
}
void pushdown(Node &u, Node &lc, Node &rc) {
if (u.tag == 1) {
swap(lc.lmax, lc.rmax);
swap(lc.lc, lc.rc);
lc.tag ^= 1;
swap(rc.lmax, rc.rmax);
swap(rc.lc, rc.rc);
rc.tag ^= 1;
u.tag = 0;
}
}
void build(int u, int l, int r) {
tr[u] = {l, r, r - l + 1, 1, 1, 1, r - l + 1, 0};
if (l == r) {
tr[u].lc = tr[u].rc = l;
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(tr[u], tr[u << 1], tr[u << 1 | 1]);
}
void modify(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) {
swap(tr[u].lmax, tr[u].rmax);
swap(tr[u].lc, tr[u].rc);
tr[u].tag ^= 1;
return;
}
pushdown(tr[u], tr[u << 1], tr[u << 1 | 1]);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) modify(u << 1, l, r);
if (r > mid) modify(u << 1 | 1, l, r);
pushup(tr[u], tr[u << 1], tr[u << 1 | 1]);
}
int query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) return tr[u].ans;
pushdown(tr[u], tr[u << 1], tr[u << 1 | 1]);
int mid = tr[u].l + tr[u].r >> 1;
int res = 0;
if (l <= mid) res = max(res, query(u << 1, l, r));
if (r > mid) res = max(res, query(u << 1 | 1, l, r));
if (l <= mid && r > mid) {
int lmax = min(mid - l + 1, tr[u << 1].len - tr[u << 1].rmax);
int rmax = min(r - mid, tr[u << 1 | 1].len - tr[u << 1 | 1].lmax);
res = max(res, lmax + rmax);
}
return res;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
char c;
scanf(" %c", &c);
a[i] = c == '7' ? 1 : 0;
}
build(1, 1, n);
while (m--) {
char op[10];
scanf("%s", op);
if (op[0] == 's') {
int l, r;
scanf("%d%d", &l, &r);
modify(1, l, r);
} else {
printf("%d\n", query(1, 1, n));
}
}
return 0;
}
```
注:本代码参考了洛谷博客:[P1907 [NOI2003] 幸运数](https://www.luogu.com.cn/blog/184141/p1907-noi2003-xing-yun-shu-ti-jie)。
阅读全文