题解:AT_abc411_c Black Intervals

· · 题解

题意

给定 n 个格子,一开始均为白色。有 q 次操作,每次操作将一个格子颜色翻转(黑变白,白变黑)。求每次操作后颜色为黑色的子段数量(即整数对 (l, r) 的数量,满足第 l 到第 r 个格子全为黑色,第 l 个格子的左边、第 r 个格子的右边均为白色)。

思路

首先,先把当前格子分成黑白两种颜色讨论:

注意到,其实如果当前修改的格子是 1 或 n 的话,不需要分类讨论(注意力惊人)。

按上述分类讨论即可。最后记得修改当前格子的颜色。

代码

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int MAXN = 5e5 + 10;

int n, q, ans, a[MAXN];

void Work() {
  int x;
  cin >> x;
  if (x == 1) {
    ans += !a[x + 1] * (!a[x] ? 1 : -1);
  } else if (x == n) {
    ans += !a[x - 1] * (!a[x] ? 1 : -1);
  } else {
    if ((!a[x] && !a[x - 1] && !a[x + 1]) || (a[x] && a[x - 1] && a[x + 1])) {
      ans++;
    } else if ((!a[x] && a[x - 1] && a[x + 1]) || (a[x] && !a[x - 1] && !a[x + 1])) {
      ans--;
    }
  }
  cout << ans << '\n';
  a[x] ^= 1;
}

int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  for (cin >> n >> q; q--; Work());
  return 0;
}