Programming exercise on 13 August

A

This problem asks to handle strings and loop structures like for statements.

According to the problem statement, it asks to find the minimum integer nn (or 1−1 if none of them does) such that:

  • 1nN21 \le n \le N-2;
  • the nn-th character of SS is A;
  • the n+1n+1-th character of SS is B;
  • the n+2n+2-th character of SS is C;

Therefore, it is sufficient to scan nn for each 1,2,,N21,2,\cdots,N−2 in a for statement, and determine for each nn if it satisfies the condition. To obtain the nn-th character of SS, most programming language provides array subscript operator S[n].

Sample codes in Python follow. (When reading a sample code, note that the index nn differs by 11, since the initial character of a string is considered as S[0].)

def main():
    N = int(input())
    S = input()
    ans = -1
    for i in range(N-2):
        if S[i] == 'A' and S[i+1] == 'B' and S[i+2] == 'C':
            ans = i + 1
            break
    print(ans)


main()

B

This problem asks to determine if an integer is a multiple of KK an appropriately use an array.

To determine if AiA_i is a multiple of KK, one can divide AiA_i by KK and check if the remainder is 00.

In most programming languages, one can find the remainder using % operator. See also the sample code.

Sample code (Python):

def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))

    result = []
    for i in range(n):
        if a[i] % k == 0:
            result.append(a[i] // k)

    print(*result)

main()

about *result

In Python, the *result syntax is used to unpack the list result, meaning it expands the list into individual elements. When you use print(*result), each element in the result list is passed as a separate argument to the print() function. Here's how it works:

  • print(result) would output the entire list as a single object, so if result is [1, 2, 3], it would print [1, 2, 3]
  • print(*result) would unpack the list and print its elements separated by spaces. For the same result list [1, 2, 3], it would print 1 2 3.

Using *result in print() is useful when you want to display the elements of the list with spaces between them, rather than displaying the list structure itself

C

This problem asks to enumerate substrings and count them without duplicates.

In order to obtain a substring in Python, it is convenient to treat the string as a list and use the slicing feature

In order to remove duplicates, it is convenient to use a data structure called set.

Sample code (Python):

def main():
    S = input()
    N = len(S)

    substrings = set()
    for L in range(1, N + 1):
      for i in range(N - L + 1):
        substrings.add(S[i:i + L])

    print(len(substrings))

main()