原题链接:登录—专业IT笔试面试备考平台_牛客网
维护一个线段树的三种不同状态
树的大小是点数的4倍,记得数组要开四倍
AC代码:
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
typedef pair<int, int> PII;
const double pi = acos(-1.0);
#define rep(i, n) for (int i = 1; i <= (n); ++i)
#define rrep(i, n) for (int i = n; i >= (1); --i)
typedef long long ll;
#define sqar(x) ((x)*(x))
const int N = 2e5 + 10;
char s[N];
struct
{
int l, r;
int c[3]; //l到r区间以i为初始值(余3的余数)区间的贡献
}tree[N << 2];
void update(int num)
{
for(int i = 0; i < 3; i++) tree[num].c[i] = tree[num << 1].c[i] + tree[num << 1 | 1].c[(i + tree[num << 1].c[i]) % 3];
}
void build_tree(int num, int l, int r)
{
tree[num].l = l, tree[num].r = r;
if(l == r)
{
if(s[l] == 'W')
{
tree[num].c[0] = 1;
tree[num].c[1] = 1;
tree[num].c[2] = 1;
}
else if(s[l] == 'L')
{
tree[num].c[0] = 0;
tree[num].c[1] = -1;
tree[num].c[2] = -1;
}
else{
tree[num].c[0] = 0;
tree[num].c[1] = 0;
tree[num].c[2] = 0;
}
}
else{
int mid = (l + r) >> 1;
build_tree(num << 1, l, mid);
build_tree(num << 1 | 1, mid + 1, r);
update(num);
}
}
int query(int num, int l, int r, int val)
{
if(tree[num].l == l && tree[num].r == r) return tree[num].c[val];
int mid = (tree[num].l + tree[num].r) >> 1;
int sum = 0;
if(l <= mid)
{
sum += query(num << 1, l, min(mid, r), val);
}
if(r > mid)
{
sum += query(num << 1 | 1, max(mid + 1, l), r, (val + sum) % 3);
}
return sum;
}
int main()
{
int n, q;
scanf("%d %d", &n, &q);
scanf("%s", s + 1);
build_tree(1, 1, n);
rep(i, q)
{
int l, r, s;
scanf("%d %d %d", &l, &r, &s);
ll res = s + query(1, l, r, s % 3);
printf("%lld\n", res);
}
return 0;
}
两个小时前学的线段树,看了大佬的题解之后自己写了一遍就过了,我好像变聪明了哈哈