D - Diagonal Separation Editorial by en_translator
Let us rephrase the conditions. When cell \((x,y)\) is black, by the first condition cells \((x,1),(x,2),\ldots,(x,y)\) must be all black. Moreover, when cell \((x,j)\) is black, by the second condition cells \((1,j),(2,j),\ldots,(x,j)\) must be all black. Thus, when cell \((x,y)\) is specified to be black, all cells in the top-left region of cell \((x,y)\) (that is, cells \((i,j)\ (1\leq i\leq x,1\leq j\leq y)\)) must be all black.
Based on this fact, the condition is satisfied if and only if:
- no \((i,j)\) satisfies \(C_i=\texttt{W}, C_j=\texttt{B},X_j\leq X_i,Y_j\leq Y_i\).
The necessity is obvious from the discussion above. The sufficiency can be demonstrated by the following construction:
- paint each cell \((x,y)\) black if there is \(i\) with \(x\leq X_i\), \(y\leq Y_i\), and \(C_i=\texttt{B}\), and white otherwise.
Now we consider how to decide if it is possible. Naive inspection costs \(O(M^2)\) time, which does not finish in time. Sort the already painted cells in lexicographical order of \((X_i,Y_i)\). Then, \(X_i\leq X_j\ (i\lt j)\) (and \(Y_i\lt Y_j\) if \(X_i=X_j\)) holds, so the condition can be rephrased as
- no \((i,j)\ (i\lt j)\) satisfies \(C_i=\texttt{W}, C_j=\texttt{B},Y_j\leq Y_i\).
This can be checked by scanning in ascending order of \(i\) while managing the minimum \(Y_i\) for \(i\) with \(C_i=\texttt{W}\).
N, M = map(int, input().split())
xyc = []
for i in range(M):
x, y, c = input().split()
xyc.append((int(x), int(y), c))
xyc.sort()
min_y = 1 << 30
ans = "Yes"
for x, y, c in xyc:
if c == "W":
min_y = min(min_y, y)
else:
if y >= min_y:
ans = "No"
print(ans)
posted:
last update: