公式

C - Black Intervals 解説 by en_translator


Here, square \(i\) will refer to the \(i\)-th square from the left among the \(N\) squares arranged from left to right.
Also, for convenience, we will add one square to each end (square \(0\) and square \((N+1)\), and assume that these squares are always painted white.

A simple solution is to flip a square and count intervals just as instructed in the problem statement, but naive implementation will cost \(O(NQ)\) or \(O(N^2Q)\) time, which hardly meets the execution time limit. Thus, we need to consider how to solve it fast.

At some point, let \(k\) be the number of indices \(i\) such that squares \(i\) and \((i+1)\) have different colors. Let \(i_1,i_2,\ldots,i_k\) be such indices \(i\). Here, the squares are painted as follows:

  • Square \(j\) is painted white for each \(0\leq j\leq i_1\).
  • Square \(j\) is painted black for each \(i_1+1\leq j\leq i_2\).
  • Square \(j\) is painted white for each \(i_2+1\leq j\leq i_3\).
  • \(\cdots\)
  • Square \(j\) is painted black for each \(i_{k-1}+1\leq j\leq i_k\).
  • Square \(j\) is painted white for each \(i_k+1\leq j\leq N+1\).

Therefore, there are \(\frac{k}{2}\) intervals of consecutively painted black cells. Here, note that \(k\) is always even, because squares \(0\) and \((N+1)\) are always painted white.

Thus, it is sufficient to count indices \(i\) such that squares \(i\) and \((i+1)\) have different colors. We will track whether squares \(i\) and \((i+1)\) have different colors.
Initially, every square is painted white, so squares \(i\) and \((i+1)\) have the same colors for all \(0\leq i\leq N\). After flipping the color of cell \(X\) \((1\leq X\leq N)\), the following two updates may occur:

  • For \(i=X-1\), if cells \(i\) and \((i+1)\) used to have the same colors, they become to have different colors; if they used to be different, they become the same.
  • For \(i=X\), if cells \(i\) and \((i+1)\) used to have the same colors, they become to have different colors; if they used to be different, they become the same.

Therefore, by one query, the number of indices \(i\), such that squares \(i\) and \((i+1)\) have different colors, either increases by two, decreases by two, or remains the same, which solely depends on whether squares \(i\) and \((i+1)\) used to have different colors before the flip. By maintaining an array to keep track of whether cells \(i\) and \((i+1)\) have different colors, as well as the number of indices \(i\) where they differ, each query can be processed in \(O(1)\) (constant) time.
Here, the overall time complexity is \(O(1)\), which is fast enough.
Hence, the problem has been solved.

Sample code in C++:

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

int main() {
	int n,q,x,s=0;
	cin >> n >> q;

	vector<int> a(n+1);
	for(int i=0;i<q;i++){
		cin >> x;
		s += (1-a[x-1])-a[x-1];
		s += (1-a[x])-a[x];
		a[x-1] = 1-a[x-1];
		a[x] = 1-a[x];
		cout << (s/2) << endl;
	}

	return 0;
}

投稿日時:
最終更新: