CF570C Replacement 题解

· · 题解

注意,这是一篇线段树题解。

在打模拟赛时写出了这种做法,赛后看到题目颜色人都傻了。

首先根据题意可以设计出线段树,每个节点存储三个信息:区间内 .. 对的数量、区间第一个字符、区间最后一个字符。

合并两个子节点时,父节点的 .. 对数量等于左子树数量加右子树数量,再加上左子树最后一个字符和右子树第一个字符形成的 .. 对(若存在)。

于是可以很容易的写出这道题的代码。

Code

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e5 + 10;
struct Node
{
    int cnt;
    char left;
    char right;
} tree[4 * MAXN];
string s;
int n, m;
void push_up(int node)
{
    int left_child = 2 * node;
    int right_child = 2 * node + 1;
    tree[node].cnt = tree[left_child].cnt + tree[right_child].cnt;
    if (tree[left_child].right == '.' and tree[right_child].left == '.'
    {
        tree[node].cnt++;
    }
    tree[node].left = tree[left_child].left;
    tree[node].right = tree[right_child].right;
}
void build(int l, int r, int node) 
{
    if (l == r)
    {
        tree[node].cnt = 0;
        tree[node].left = s[l];
        tree[node].right = s[l];
        return;
    }
    int mid = (l + r) / 2;
    build(l, mid, 2 * node);
    build(mid + 1, r, 2 * node + 1);
    push_up(node);
}
void update(int pos, char c, int l, int r, int node)
{
    if (l == r)
    {
        tree[node].left = c;
        tree[node].right = c;
        return;
    }
    int mid = (l + r) / 2;
    if (pos <= mid)
    {
        update(pos, c, l, mid, 2 * node);
    }
    else
    {
        update(pos, c, mid + 1, r, 2 * node + 1);
    }
    push_up(node);
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> m;
    cin >> s;
    build(0, n - 1, 1);
    while (m--)
    {
        int x;
        char c;
        cin >> x >> c;
        x--;
        update(x, c, 0, n - 1, 1);
        cout << tree[1].cnt << '\n';
    }
    return 0;
}

AC记录