+ , -- or ?#12270

+ , -- or ? (Editorial)

Problem Author:

Hasan Saleh (MathModel)

Prepared by:

Hasan Saleh (MathModel)

Edited by:

Hasan Saleh (MathModel)

Solution

We first convert the array to a string of length n-1 as follows:

t_i = \begin{cases} \texttt{+} & \text{if } a_i < a_{i+1},\\ \texttt{-} & \text{if } a_i > a_{i+1},\\ \texttt{?} & \text{if } a_i = a_{i+1}. \end{cases}

Now the problem is: does appear as a substring of under the matching rule

t_{i+j} = \texttt{?} \;\;\text{or}\;\; s_j = \texttt{?} \;\;\text{or}\;\; t_{i+j} = s_j.

Because the constraints are small , we can simply try every starting position. For every with 0 \le i \le (n-1)-k we check all from to k-1. If for some the above condition fails, then this window is bad. If we find a window for which it holds for all , we answer YES. If none of the windows works, we answer NO.

Formally, we answer YES iff

\exists i \;\; \forall j \in [0,k-1]: \bigl(t_{i+j} = \texttt{?} \lor s_j = \texttt{?} \lor t_{i+j} = s_j \bigr).

The complexity per test is : building takes , and we check at most windows, each in . This fits the given bound on \sum n\cdot k. The sample tests follow directly from this rule: whenever the array-difference string can be read as the pattern after interpreting some '?' as '+' or '-', the answer is YES; otherwise it is NO.

Complexity .

def solve():
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    s=input().strip()
    t=[]
    for i in range(n-1):
        if a[i]<a[i+1]: t.append('+')
        elif a[i]>a[i+1]: t.append('-')
        else: t.append('?')
    ok=False
    for i in range(n-1-k+1):
        good=True
        for j in range(k):
            x=t[i+j]; y=s[j]
            if x=='?' or y=='?': continue
            if x!=y:
                good=False
                break
        if good:
            ok=True
            break
    print("YES" if ok else "NO")

for _ in range(int(input())):
    solve()