题解:AT_abc411_c [ABC411C] Black Intervals

· · 题解

题目翻译

有 N 个方格从左到右排列成一行。初始时所有方格都是白色的。
处理 Q 个查询,第 i 个查询给出一个整数 A_i(在 1 到 N 之间),执行以下操作:

分析

解法

  1. 初始化长度为 N 的数组 c,所有元素为 0(白色),ans = 0。
  2. 对于每个查询 A_i(位置 x):
    • 记录 x 的原始颜色 old = c[x] 和左右邻居颜色(边界视为白色)。
    • 翻转 c[x] = 1 - old。
    • 根据翻转后 c[x] 的颜色和邻居颜色更新 ans:
      • 变黑:左右白则 ans+1,左右黑则 ans-1。
      • 变白:左右白则 ans-1,左右黑则 ans+1。
  3. 输出每次查询后的 ans。

代码

#include <bits/stdc++.h>
using namespace std;

const int MX = 500010; // 最大数组大小

int n, q;
int a[MX]; // 存储查询
int c[MX]; // 颜色数组,0白1黑

int main(){
    scanf("%d%d", &n, &q);
    for(int i = 1;i <= q;i++){
        scanf("%d", &a[i]); // 读入查询
    }

    int ans = 0;
    // 初始化颜色数组为0(白色)
    for(int i = 1;i <= n;i++){
        c[i] = 0;
    }

    for(int i = 1;i <= q;i++){
        int x = a[i]; // 当前查询位置
        int old = c[x]; // 原始颜色
        int l = (x - 1 >= 1) ? c[x - 1] : 0; // 左邻居颜色(边界为0)
        int r = (x + 1 <= n) ? c[x + 1] : 0; // 右邻居颜色(边界为0)

        c[x] = 1 - old; // 翻转颜色

        if(c[x] == 1){ // 变黑
            if(l == 0 && r == 0){
                ans++; // 新增独立区间
            }
            else if(l == 1 && r == 1){
                ans--; // 连接两个区间
            }
        }
        else{ // 变白
            if(l == 0 && r == 0){
                ans--; // 减少独立区间
            }
            else if(l == 1 && r == 1){
                ans++; // 分裂成两个区间
            }
        }
        printf("%d\n", ans); // 输出当前答案
    }
    return 0;
}

总结